blob: 763bfe9cbd17b98e31989e2d354b48c26017a387 [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 Chartier590fee92013-09-13 13:46:47 -070077 : non_moving_space_(NULL),
78 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),
131 bump_pointer_space_(nullptr),
132 temp_space_(nullptr),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800133 reference_referent_offset_(0),
134 reference_queue_offset_(0),
135 reference_queueNext_offset_(0),
136 reference_pendingNext_offset_(0),
137 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700138 min_free_(min_free),
139 max_free_(max_free),
140 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700141 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700142 total_allocation_time_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700143 verify_object_mode_(kHeapVerificationNotPermitted),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700144 gc_disable_count_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700145 running_on_valgrind_(RUNNING_ON_VALGRIND) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800146 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800147 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700148 }
149
Ian Rogers1d54e732013-05-02 21:10:01 -0700150 live_bitmap_.reset(new accounting::HeapBitmap(this));
151 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700152
Ian Rogers30fab402012-01-23 15:43:46 -0800153 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700154 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800155 if (!image_file_name.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700156 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700157 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700158 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800159 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
160 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800161 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
162 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700163 if (oat_file_end_addr > requested_alloc_space_begin) {
164 requested_alloc_space_begin =
165 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
166 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700167 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700168 }
169
Mathieu Chartier590fee92013-09-13 13:46:47 -0700170 const char* name = Runtime::Current()->IsZygote() ? "zygote space" : "alloc space";
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700171 if (!kUseRosAlloc) {
172 non_moving_space_ = space::DlMallocSpace::Create(name, initial_size, growth_limit, capacity,
173 requested_alloc_space_begin);
174 } else {
175 non_moving_space_ = space::RosAllocSpace::Create(name, initial_size, growth_limit, capacity,
176 requested_alloc_space_begin);
177 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700178 if (kMovingCollector) {
179 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
180 // TODO: Having 3+ spaces as big as the large heap size can cause virtual memory fragmentation
181 // issues.
182 const size_t bump_pointer_space_size = std::min(non_moving_space_->Capacity(), 128 * MB);
183 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space",
184 bump_pointer_space_size, nullptr);
185 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
186 AddSpace(bump_pointer_space_);
187 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2", bump_pointer_space_size,
188 nullptr);
189 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
190 AddSpace(temp_space_);
191 }
192
193 CHECK(non_moving_space_ != NULL) << "Failed to create non-moving space";
194 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
195 AddSpace(non_moving_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700196
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700197 // Allocate the large object space.
198 const bool kUseFreeListSpaceForLOS = false;
199 if (kUseFreeListSpaceForLOS) {
200 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
201 } else {
202 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
203 }
204 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700205 AddSpace(large_object_space_);
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700206
Ian Rogers1d54e732013-05-02 21:10:01 -0700207 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700208 CHECK(!continuous_spaces_.empty());
209 // Relies on the spaces being sorted.
Ian Rogers1d54e732013-05-02 21:10:01 -0700210 byte* heap_begin = continuous_spaces_.front()->Begin();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700211 byte* heap_end = continuous_spaces_.back()->Limit();
212 size_t heap_capacity = heap_end - heap_begin;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700213
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800214 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700215 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700216 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700217
Mathieu Chartier590fee92013-09-13 13:46:47 -0700218 // Card cache for now since it makes it easier for us to update the references to the copying
219 // spaces.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700220 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier590fee92013-09-13 13:46:47 -0700221 new accounting::ModUnionTableCardCache("Image mod-union table", this, GetImageSpace());
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700222 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
223 AddModUnionTable(mod_union_table);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700224
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700225 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700226 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700227
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800228 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700229 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700230 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
231 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
232 max_allocation_stack_size_));
233 live_stack_.reset(accounting::ObjectStack::Create("live stack",
234 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700235
Mathieu Chartier65db8802012-11-20 12:36:46 -0800236 // It's still too early to take a lock because there are no threads yet, but we can create locks
237 // now. We don't create it earlier to make it clear that you can't use locks during heap
238 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700239 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700240 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
241 *gc_complete_lock_));
Ian Rogers1d54e732013-05-02 21:10:01 -0700242 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800243 last_gc_size_ = GetBytesAllocated();
244
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700245 if (ignore_max_footprint_) {
246 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700247 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700248 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700249 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700250
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800251 // Create our garbage collectors.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700252 if (!kMovingCollector) {
253 for (size_t i = 0; i < 2; ++i) {
254 const bool concurrent = i != 0;
255 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
256 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
257 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
258 }
259 } else {
260 semi_space_collector_ = new collector::SemiSpace(this);
261 garbage_collectors_.push_back(semi_space_collector_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700262 }
263
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700264 if (running_on_valgrind_) {
Ian Rogersfa824272013-11-05 16:12:57 -0800265 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700266 }
267
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800268 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800269 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700270 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700271}
272
Mathieu Chartier590fee92013-09-13 13:46:47 -0700273bool Heap::IsCompilingBoot() const {
274 for (const auto& space : continuous_spaces_) {
275 if (space->IsImageSpace()) {
276 return false;
277 } else if (space->IsZygoteSpace()) {
278 return false;
279 }
280 }
281 return true;
282}
283
284bool Heap::HasImageSpace() const {
285 for (const auto& space : continuous_spaces_) {
286 if (space->IsImageSpace()) {
287 return true;
288 }
289 }
290 return false;
291}
292
293void Heap::IncrementDisableGC(Thread* self) {
294 // Need to do this holding the lock to prevent races where the GC is about to run / running when
295 // we attempt to disable it.
296 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
297 MutexLock mu(self, *gc_complete_lock_);
298 WaitForGcToCompleteLocked(self);
299 ++gc_disable_count_;
300}
301
302void Heap::DecrementDisableGC(Thread* self) {
303 MutexLock mu(self, *gc_complete_lock_);
304 CHECK_GE(gc_disable_count_, 0U);
305 --gc_disable_count_;
306}
307
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700308void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700309 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
310 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800311 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700312 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700313}
314
Mathieu Chartier590fee92013-09-13 13:46:47 -0700315void Heap::VisitObjects(ObjectVisitorCallback callback, void* arg) {
316 // Visit objects in bump pointer space.
317 Thread* self = Thread::Current();
318 // TODO: Use reference block.
319 std::vector<SirtRef<mirror::Object>*> saved_refs;
320 if (bump_pointer_space_ != nullptr) {
321 // Need to put all these in sirts since the callback may trigger a GC. TODO: Use a better data
322 // structure.
323 mirror::Object* obj = reinterpret_cast<mirror::Object*>(bump_pointer_space_->Begin());
324 const mirror::Object* end = reinterpret_cast<const mirror::Object*>(
325 bump_pointer_space_->End());
326 while (obj < end) {
327 saved_refs.push_back(new SirtRef<mirror::Object>(self, obj));
328 obj = space::BumpPointerSpace::GetNextObject(obj);
329 }
330 }
331 // TODO: Switch to standard begin and end to use ranged a based loop.
332 for (mirror::Object** it = allocation_stack_->Begin(), **end = allocation_stack_->End();
333 it < end; ++it) {
334 mirror::Object* obj = *it;
335 // Objects in the allocation stack might be in a movable space.
336 saved_refs.push_back(new SirtRef<mirror::Object>(self, obj));
337 }
338 GetLiveBitmap()->Walk(callback, arg);
339 for (const auto& ref : saved_refs) {
340 callback(ref->get(), arg);
341 }
342 // Need to free the sirts in reverse order they were allocated.
343 for (size_t i = saved_refs.size(); i != 0; --i) {
344 delete saved_refs[i - 1];
345 }
346}
347
348void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
349 MarkAllocStack(non_moving_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(), stack);
350}
351
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700352void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700353 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700354}
355
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700356static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700357 DCHECK(out_value != NULL);
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700358 jfieldID field = env->GetStaticFieldID(clz, name, "I");
359 if (field == NULL) {
360 env->ExceptionClear();
361 return false;
362 }
363 *out_value = env->GetStaticIntField(clz, field);
364 return true;
365}
366
367void Heap::ListenForProcessStateChange() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700368 VLOG(heap) << "Heap notified of process state change";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700369
370 Thread* self = Thread::Current();
371 JNIEnvExt* env = self->GetJniEnv();
372
373 if (!have_zygote_space_) {
374 return;
375 }
376
377 if (activity_thread_class_ == NULL) {
378 jclass clz = env->FindClass("android/app/ActivityThread");
379 if (clz == NULL) {
380 env->ExceptionClear();
381 LOG(WARNING) << "Could not find activity thread class in process state change";
382 return;
383 }
384 activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
385 }
386
387 if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
388 jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
389 "currentActivityThread",
390 "()Landroid/app/ActivityThread;");
391 if (current_activity_method == NULL) {
392 env->ExceptionClear();
393 LOG(WARNING) << "Could not get method for currentActivityThread";
394 return;
395 }
396
397 jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
398 if (obj == NULL) {
399 env->ExceptionClear();
400 LOG(WARNING) << "Could not get current activity";
401 return;
402 }
403 activity_thread_ = env->NewGlobalRef(obj);
404 }
405
406 if (process_state_cares_about_pause_time_.empty()) {
407 // Just attempt to do this the first time.
408 jclass clz = env->FindClass("android/app/ActivityManager");
409 if (clz == NULL) {
410 LOG(WARNING) << "Activity manager class is null";
411 return;
412 }
413 ScopedLocalRef<jclass> activity_manager(env, clz);
414 std::vector<const char*> care_about_pauses;
415 care_about_pauses.push_back("PROCESS_STATE_TOP");
416 care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
417 // Attempt to read the constants and classify them as whether or not we care about pause times.
418 for (size_t i = 0; i < care_about_pauses.size(); ++i) {
419 int process_state = 0;
420 if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
421 process_state_cares_about_pause_time_.insert(process_state);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700422 VLOG(heap) << "Adding process state " << process_state
423 << " to set of states which care about pause time";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700424 }
425 }
426 }
427
428 if (application_thread_class_ == NULL) {
429 jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
430 if (clz == NULL) {
431 env->ExceptionClear();
432 LOG(WARNING) << "Could not get application thread class";
433 return;
434 }
435 application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
436 last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
437 if (last_process_state_id_ == NULL) {
438 env->ExceptionClear();
439 LOG(WARNING) << "Could not get last process state member";
440 return;
441 }
442 }
443
444 if (application_thread_class_ != NULL && application_thread_ == NULL) {
445 jmethodID get_application_thread =
446 env->GetMethodID(activity_thread_class_, "getApplicationThread",
447 "()Landroid/app/ActivityThread$ApplicationThread;");
448 if (get_application_thread == NULL) {
449 LOG(WARNING) << "Could not get method ID for get application thread";
450 return;
451 }
452
453 jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
454 if (obj == NULL) {
455 LOG(WARNING) << "Could not get application thread";
456 return;
457 }
458
459 application_thread_ = env->NewGlobalRef(obj);
460 }
461
462 if (application_thread_ != NULL && last_process_state_id_ != NULL) {
463 int process_state = env->GetIntField(application_thread_, last_process_state_id_);
464 env->ExceptionClear();
465
466 care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
467 process_state_cares_about_pause_time_.end();
468
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700469 VLOG(heap) << "New process state " << process_state
470 << " care about pauses " << care_about_pause_times_;
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700471 }
Mathieu Chartier82353312013-07-18 10:47:51 -0700472}
473
Mathieu Chartier590fee92013-09-13 13:46:47 -0700474void Heap::AddSpace(space::Space* space) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700475 DCHECK(space != NULL);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700476 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
477 if (space->IsContinuousSpace()) {
478 DCHECK(!space->IsDiscontinuousSpace());
479 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
480 // Continuous spaces don't necessarily have bitmaps.
481 accounting::SpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
482 accounting::SpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
483 if (live_bitmap != nullptr) {
484 DCHECK(mark_bitmap != nullptr);
485 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
486 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700487 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700488
489 continuous_spaces_.push_back(continuous_space);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700490 if (continuous_space->IsMallocSpace()) {
491 non_moving_space_ = continuous_space->AsMallocSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700492 }
493
494 // Ensure that spaces remain sorted in increasing order of start address.
495 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
496 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
497 return a->Begin() < b->Begin();
498 });
499 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
500 // avoid redundant marking.
501 bool seen_zygote = false, seen_alloc = false;
502 for (const auto& space : continuous_spaces_) {
503 if (space->IsImageSpace()) {
504 CHECK(!seen_zygote);
505 CHECK(!seen_alloc);
506 } else if (space->IsZygoteSpace()) {
507 CHECK(!seen_alloc);
508 seen_zygote = true;
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700509 } else if (space->IsMallocSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700510 seen_alloc = true;
511 }
512 }
513 } else {
514 DCHECK(space->IsDiscontinuousSpace());
515 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
516 DCHECK(discontinuous_space->GetLiveObjects() != nullptr);
517 live_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetLiveObjects());
518 DCHECK(discontinuous_space->GetMarkObjects() != nullptr);
519 mark_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetMarkObjects());
520 discontinuous_spaces_.push_back(discontinuous_space);
521 }
522 if (space->IsAllocSpace()) {
523 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700524 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800525}
526
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700527void Heap::RegisterGCAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700528 if (this != nullptr) {
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700529 gc_memory_overhead_.fetch_add(bytes);
530 }
531}
532
533void Heap::RegisterGCDeAllocation(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_sub(bytes);
536 }
537}
538
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700539void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700540 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700541 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700542 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800543
544 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800545 uint64_t total_paused_time = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700546 for (const auto& collector : garbage_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800547 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800548 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700549 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800550 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700551 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800552 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
553 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
554 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700555 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
556 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
557 << collector->GetName() << " freed: " << freed_objects
558 << " objects with total size " << PrettySize(freed_bytes) << "\n"
559 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
560 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800561 total_duration += total_ns;
562 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700563 }
564 }
565 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700566 size_t total_objects_allocated = GetObjectsAllocatedEver();
567 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700568 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700569 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700570 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
571 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700572 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700573 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700574 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700575 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700576 os << "Total number of allocations: " << total_objects_allocated << "\n";
577 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700578 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700579 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
580 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
581 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700582 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700583 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
584 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700585 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700586}
587
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800588Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700589 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700590 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700591 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700592 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700593 STLDeleteElements(&garbage_collectors_);
594 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700595 allocation_stack_->Reset();
596 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700597 STLDeleteValues(&mod_union_tables_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700598 STLDeleteElements(&continuous_spaces_);
599 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700600 delete gc_complete_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700601 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700602}
603
Ian Rogers1d54e732013-05-02 21:10:01 -0700604space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
605 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700606 for (const auto& space : continuous_spaces_) {
607 if (space->Contains(obj)) {
608 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700609 }
610 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700611 if (!fail_ok) {
612 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
613 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700614 return NULL;
615}
616
Ian Rogers1d54e732013-05-02 21:10:01 -0700617space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
618 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700619 for (const auto& space : discontinuous_spaces_) {
620 if (space->Contains(obj)) {
621 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700622 }
623 }
624 if (!fail_ok) {
625 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
626 }
627 return NULL;
628}
629
630space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
631 space::Space* result = FindContinuousSpaceFromObject(obj, true);
632 if (result != NULL) {
633 return result;
634 }
635 return FindDiscontinuousSpaceFromObject(obj, true);
636}
637
Mathieu Chartier39e32612013-11-12 16:28:05 -0800638struct SoftReferenceArgs {
639 RootVisitor* is_marked_callback_;
640 RootVisitor* recursive_mark_callback_;
641 void* arg_;
642};
643
644mirror::Object* Heap::PreserveSoftReferenceCallback(mirror::Object* obj, void* arg) {
645 SoftReferenceArgs* args = reinterpret_cast<SoftReferenceArgs*>(arg);
646 // TODO: Not preserve all soft references.
647 return args->recursive_mark_callback_(obj, args->arg_);
648}
649
650// Process reference class instances and schedule finalizations.
651void Heap::ProcessReferences(TimingLogger& timings, bool clear_soft,
652 RootVisitor* is_marked_callback,
653 RootVisitor* recursive_mark_object_callback, void* arg) {
654 // Unless we are in the zygote or required to clear soft references with white references,
655 // preserve some white referents.
656 if (!clear_soft && !Runtime::Current()->IsZygote()) {
657 SoftReferenceArgs soft_reference_args;
658 soft_reference_args.is_marked_callback_ = is_marked_callback;
659 soft_reference_args.recursive_mark_callback_ = recursive_mark_object_callback;
660 soft_reference_args.arg_ = arg;
661 soft_reference_queue_.PreserveSomeSoftReferences(&PreserveSoftReferenceCallback,
662 &soft_reference_args);
663 }
664 timings.StartSplit("ProcessReferences");
665 // Clear all remaining soft and weak references with white referents.
666 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
667 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
668 timings.EndSplit();
669 // Preserve all white objects with finalize methods and schedule them for finalization.
670 timings.StartSplit("EnqueueFinalizerReferences");
671 finalizer_reference_queue_.EnqueueFinalizerReferences(cleared_references_, is_marked_callback,
672 recursive_mark_object_callback, arg);
673 timings.EndSplit();
674 timings.StartSplit("ProcessReferences");
675 // Clear all f-reachable soft and weak references with white referents.
676 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
677 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
678 // Clear all phantom references with white referents.
679 phantom_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
680 // At this point all reference queues other than the cleared references should be empty.
681 DCHECK(soft_reference_queue_.IsEmpty());
682 DCHECK(weak_reference_queue_.IsEmpty());
683 DCHECK(finalizer_reference_queue_.IsEmpty());
684 DCHECK(phantom_reference_queue_.IsEmpty());
685 timings.EndSplit();
686}
687
688bool Heap::IsEnqueued(mirror::Object* ref) const {
689 // Since the references are stored as cyclic lists it means that once enqueued, the pending next
690 // will always be non-null.
691 return ref->GetFieldObject<mirror::Object*>(GetReferencePendingNextOffset(), false) != nullptr;
692}
693
694bool Heap::IsEnqueuable(const mirror::Object* ref) const {
695 DCHECK(ref != nullptr);
696 const mirror::Object* queue =
697 ref->GetFieldObject<mirror::Object*>(GetReferenceQueueOffset(), false);
698 const mirror::Object* queue_next =
699 ref->GetFieldObject<mirror::Object*>(GetReferenceQueueNextOffset(), false);
700 return queue != nullptr && queue_next == nullptr;
701}
702
703// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
704// marked, put it on the appropriate list in the heap for later processing.
705void Heap::DelayReferenceReferent(mirror::Class* klass, mirror::Object* obj,
706 RootVisitor mark_visitor, void* arg) {
707 DCHECK(klass != nullptr);
708 DCHECK(klass->IsReferenceClass());
709 DCHECK(obj != nullptr);
710 mirror::Object* referent = GetReferenceReferent(obj);
711 if (referent != nullptr) {
712 mirror::Object* forward_address = mark_visitor(referent, arg);
713 // Null means that the object is not currently marked.
714 if (forward_address == nullptr) {
715 Thread* self = Thread::Current();
716 // TODO: Remove these locks, and use atomic stacks for storing references?
717 // We need to check that the references haven't already been enqueued since we can end up
718 // scanning the same reference multiple times due to dirty cards.
719 if (klass->IsSoftReferenceClass()) {
720 soft_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
721 } else if (klass->IsWeakReferenceClass()) {
722 weak_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
723 } else if (klass->IsFinalizerReferenceClass()) {
724 finalizer_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
725 } else if (klass->IsPhantomReferenceClass()) {
726 phantom_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
727 } else {
728 LOG(FATAL) << "Invalid reference type " << PrettyClass(klass) << " " << std::hex
729 << klass->GetAccessFlags();
730 }
731 } else if (referent != forward_address) {
732 // Referent is already marked and we need to update it.
733 SetReferenceReferent(obj, forward_address);
734 }
735 }
736}
737
Ian Rogers1d54e732013-05-02 21:10:01 -0700738space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700739 for (const auto& space : continuous_spaces_) {
740 if (space->IsImageSpace()) {
741 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700742 }
743 }
744 return NULL;
745}
746
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700747static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700748 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700749 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700750 size_t chunk_free_bytes = chunk_size - used_bytes;
751 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
752 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700753 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700754}
755
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700756void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, bool large_object_allocation) {
757 std::ostringstream oss;
758 int64_t total_bytes_free = GetFreeMemory();
759 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
760 << " free bytes";
761 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
762 if (!large_object_allocation && total_bytes_free >= byte_count) {
763 size_t max_contiguous_allocation = 0;
764 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700765 if (space->IsMallocSpace()) {
766 // To allow the Walk/InspectAll() to exclusively-lock the mutator
767 // lock, temporarily release the shared access to the mutator
768 // lock here by transitioning to the suspended state.
769 Locks::mutator_lock_->AssertSharedHeld(self);
770 self->TransitionFromRunnableToSuspended(kSuspended);
771 space->AsMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
772 self->TransitionFromSuspendedToRunnable();
773 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700774 }
775 }
776 oss << "; failed due to fragmentation (largest possible contiguous allocation "
777 << max_contiguous_allocation << " bytes)";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700778 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700779 self->ThrowOutOfMemoryError(oss.str().c_str());
780}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700781
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700782inline bool Heap::TryAllocLargeObjectInstrumented(Thread* self, mirror::Class* c, size_t byte_count,
783 mirror::Object** obj_ptr, size_t* bytes_allocated) {
784 bool large_object_allocation = ShouldAllocLargeObject(c, byte_count);
Ian Rogers333cf1b2013-07-24 11:57:02 -0700785 if (UNLIKELY(large_object_allocation)) {
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700786 mirror::Object* obj = AllocateInstrumented(self, large_object_space_, byte_count, bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700787 // Make sure that our large object didn't get placed anywhere within the space interval or else
788 // it breaks the immune range.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700789 DCHECK(obj == nullptr ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700790 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
791 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700792 *obj_ptr = obj;
793 }
794 return large_object_allocation;
795}
796
Mathieu Chartier590fee92013-09-13 13:46:47 -0700797mirror::Object* Heap::AllocMovableObjectInstrumented(Thread* self, mirror::Class* c,
798 size_t byte_count) {
799 DebugCheckPreconditionsForAllocObject(c, byte_count);
800 mirror::Object* obj;
801 AllocationTimer alloc_timer(this, &obj);
802 byte_count = RoundUp(byte_count, 8);
803 if (UNLIKELY(IsOutOfMemoryOnAllocation(byte_count, false))) {
804 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, false);
805 if (UNLIKELY(IsOutOfMemoryOnAllocation(byte_count, true))) {
806 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
807 }
808 }
809 obj = bump_pointer_space_->AllocNonvirtual(byte_count);
810 if (LIKELY(obj != NULL)) {
811 obj->SetClass(c);
812 DCHECK(!obj->IsClass());
813 // Record allocation after since we want to use the atomic add for the atomic fence to guard
814 // the SetClass since we do not want the class to appear NULL in another thread.
815 num_bytes_allocated_.fetch_add(byte_count);
816 if (Runtime::Current()->HasStatsEnabled()) {
817 RuntimeStats* thread_stats = Thread::Current()->GetStats();
818 ++thread_stats->allocated_objects;
819 thread_stats->allocated_bytes += byte_count;
820 RuntimeStats* global_stats = Runtime::Current()->GetStats();
821 ++global_stats->allocated_objects;
822 global_stats->allocated_bytes += byte_count;
823 }
824 if (Dbg::IsAllocTrackingEnabled()) {
825 Dbg::RecordAllocation(c, byte_count);
826 }
827 if (kDesiredHeapVerification > kNoHeapVerification) {
828 VerifyObject(obj);
829 }
830 } else {
831 ThrowOutOfMemoryError(self, byte_count, false);
832 }
833 if (kIsDebugBuild) {
834 self->VerifyStack();
835 }
836 return obj;
837}
838
839mirror::Object* Heap::AllocNonMovableObjectInstrumented(Thread* self, mirror::Class* c,
840 size_t byte_count) {
841 DebugCheckPreconditionsForAllocObject(c, byte_count);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700842 mirror::Object* obj;
843 size_t bytes_allocated;
844 AllocationTimer alloc_timer(this, &obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700845 bool large_object_allocation = TryAllocLargeObjectInstrumented(self, c, byte_count, &obj,
846 &bytes_allocated);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700847 if (LIKELY(!large_object_allocation)) {
848 // Non-large object allocation.
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700849 if (!kUseRosAlloc) {
850 DCHECK(non_moving_space_->IsDlMallocSpace());
851 obj = AllocateInstrumented(self, reinterpret_cast<space::DlMallocSpace*>(non_moving_space_),
852 byte_count, &bytes_allocated);
853 } else {
854 DCHECK(non_moving_space_->IsRosAllocSpace());
855 obj = AllocateInstrumented(self, reinterpret_cast<space::RosAllocSpace*>(non_moving_space_),
856 byte_count, &bytes_allocated);
857 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700858 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700859 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700860 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700861 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700862 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700863 // Record allocation after since we want to use the atomic add for the atomic fence to guard
864 // the SetClass since we do not want the class to appear NULL in another thread.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700865 size_t new_num_bytes_allocated = RecordAllocationInstrumented(bytes_allocated, obj);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700866 if (Dbg::IsAllocTrackingEnabled()) {
867 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700868 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700869 CheckConcurrentGC(self, new_num_bytes_allocated, obj);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700870 if (kDesiredHeapVerification > kNoHeapVerification) {
871 VerifyObject(obj);
872 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700873 } else {
874 ThrowOutOfMemoryError(self, byte_count, large_object_allocation);
Carl Shapiro58551df2011-07-24 03:09:51 -0700875 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700876 if (kIsDebugBuild) {
877 self->VerifyStack();
878 }
879 return obj;
Carl Shapiro58551df2011-07-24 03:09:51 -0700880}
881
Mathieu Chartier590fee92013-09-13 13:46:47 -0700882void Heap::Trim() {
883 uint64_t start_ns = NanoTime();
884 // Trim the managed spaces.
885 uint64_t total_alloc_space_allocated = 0;
886 uint64_t total_alloc_space_size = 0;
887 uint64_t managed_reclaimed = 0;
888 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700889 if (space->IsMallocSpace() && !space->IsZygoteSpace()) {
890 gc::space::MallocSpace* alloc_space = space->AsMallocSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700891 total_alloc_space_size += alloc_space->Size();
892 managed_reclaimed += alloc_space->Trim();
893 }
894 }
895 total_alloc_space_allocated = GetBytesAllocated() - large_object_space_->GetBytesAllocated() -
896 bump_pointer_space_->GetBytesAllocated();
897 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
898 static_cast<float>(total_alloc_space_size);
899 uint64_t gc_heap_end_ns = NanoTime();
900 // Trim the native heap.
901 dlmalloc_trim(0);
902 size_t native_reclaimed = 0;
903 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
904 uint64_t end_ns = NanoTime();
905 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
906 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
907 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
908 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
909 << "%.";
910}
911
912bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
913 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
914 // taking the lock.
915 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -0700916 return true;
917 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700918 return IsAligned<kObjectAlignment>(obj) && IsHeapAddress(obj);
919}
920
921bool Heap::IsHeapAddress(const mirror::Object* obj) const {
922 if (kMovingCollector && bump_pointer_space_->HasAddress(obj)) {
923 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700924 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700925 // TODO: This probably doesn't work for large objects.
926 return FindSpaceFromObject(obj, true) != nullptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700927}
928
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700929bool Heap::IsLiveObjectLocked(const mirror::Object* obj, bool search_allocation_stack,
930 bool search_live_stack, bool sorted) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700931 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700932 if (obj == nullptr || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700933 return false;
934 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700935 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
936 space::DiscontinuousSpace* d_space = NULL;
937 if (c_space != NULL) {
938 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700939 return true;
940 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700941 } else if (bump_pointer_space_->Contains(obj) || temp_space_->Contains(obj)) {
942 return true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700943 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700944 d_space = FindDiscontinuousSpaceFromObject(obj, true);
945 if (d_space != NULL) {
946 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700947 return true;
948 }
949 }
950 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700951 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700952 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
953 if (i > 0) {
954 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -0700955 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700956 if (search_allocation_stack) {
957 if (sorted) {
958 if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
959 return true;
960 }
961 } else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
962 return true;
963 }
964 }
965
966 if (search_live_stack) {
967 if (sorted) {
968 if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
969 return true;
970 }
971 } else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
972 return true;
973 }
974 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700975 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700976 // We need to check the bitmaps again since there is a race where we mark something as live and
977 // then clear the stack containing it.
978 if (c_space != NULL) {
979 if (c_space->GetLiveBitmap()->Test(obj)) {
980 return true;
981 }
982 } else {
983 d_space = FindDiscontinuousSpaceFromObject(obj, true);
984 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
985 return true;
986 }
987 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700988 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700989}
990
Ian Rogers04d7aa92013-03-16 14:29:17 -0700991void Heap::VerifyObjectImpl(const mirror::Object* obj) {
992 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700993 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700994 return;
995 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700996 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700997}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700998
Mathieu Chartier590fee92013-09-13 13:46:47 -0700999void Heap::DumpSpaces(std::ostream& stream) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001000 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001001 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1002 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001003 stream << space << " " << *space << "\n";
1004 if (live_bitmap != nullptr) {
1005 stream << live_bitmap << " " << *live_bitmap << "\n";
1006 }
1007 if (mark_bitmap != nullptr) {
1008 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1009 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001010 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001011 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001012 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001013 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001014}
1015
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001016void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001017 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
1018 // Ignore early dawn of the universe verifications.
1019 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.load()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001020 return;
1021 }
1022 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
1023 mirror::Object::ClassOffset().Int32Value();
1024 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
1025 if (UNLIKELY(c == NULL)) {
1026 LOG(FATAL) << "Null class in object: " << obj;
1027 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
1028 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
1029 }
1030 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
1031 // Note: we don't use the accessors here as they have internal sanity checks
1032 // that we don't want to run
1033 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
1034 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
1035 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
1036 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
1037 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001038
Mathieu Chartier590fee92013-09-13 13:46:47 -07001039 if (verify_object_mode_ > kVerifyAllFast) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001040 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
1041 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -07001042 if (!IsLiveObjectLocked(obj)) {
1043 DumpSpaces();
1044 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001045 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001046 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001047 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
1048 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001049 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001050}
1051
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001052void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001053 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001054 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001055}
1056
1057void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001058 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001059 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001060}
1061
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001062inline size_t Heap::RecordAllocationInstrumented(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001063 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001064 DCHECK_GT(size, 0u);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001065 size_t old_num_bytes_allocated = static_cast<size_t>(num_bytes_allocated_.fetch_add(size));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001066
1067 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001068 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001069 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001070 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001071
1072 // TODO: Update these atomically.
1073 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1074 ++global_stats->allocated_objects;
1075 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001076 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001077
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001078 // This is safe to do since the GC will never free objects which are neither in the allocation
1079 // stack or the live bitmap.
1080 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001081 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001082 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001083
1084 return old_num_bytes_allocated + size;
Carl Shapiro58551df2011-07-24 03:09:51 -07001085}
1086
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001087void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001088 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001089 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001090
1091 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001092 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001093 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001094 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001095
1096 // TODO: Do this concurrently.
1097 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1098 global_stats->freed_objects += freed_objects;
1099 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001100 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001101}
1102
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001103inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::AllocSpace* space, size_t alloc_size,
1104 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -07001105 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001106 return NULL;
1107 }
1108 return space->Alloc(self, alloc_size, bytes_allocated);
1109}
1110
1111// DlMallocSpace-specific version.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001112inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
1113 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -07001114 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001115 return nullptr;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001116 }
Mathieu Chartier720ef762013-08-17 14:46:54 -07001117 if (LIKELY(!running_on_valgrind_)) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001118 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
1119 } else {
1120 return space->Alloc(self, alloc_size, bytes_allocated);
1121 }
1122}
1123
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001124// RosAllocSpace-specific version.
1125inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::RosAllocSpace* space, size_t alloc_size,
1126 bool grow, size_t* bytes_allocated) {
1127 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
1128 return NULL;
1129 }
1130 if (LIKELY(!running_on_valgrind_)) {
1131 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
1132 } else {
1133 return space->Alloc(self, alloc_size, bytes_allocated);
1134 }
1135}
1136
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001137template <class T>
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001138inline mirror::Object* Heap::AllocateInstrumented(Thread* self, T* space, size_t alloc_size,
1139 size_t* bytes_allocated) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001140 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
1141 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -07001142 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001143 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -07001144
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001145 mirror::Object* ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
1146 if (LIKELY(ptr != NULL)) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001147 return ptr;
1148 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001149 return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
1150}
1151
Mathieu Chartier720ef762013-08-17 14:46:54 -07001152mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space,
1153 size_t alloc_size, size_t* bytes_allocated) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001154 mirror::Object* ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001155
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001156 // The allocation failed. If the GC is running, block until it completes, and then retry the
1157 // allocation.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001158 collector::GcType last_gc = WaitForGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001159 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001160 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001161 ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001162 if (ptr != NULL) {
1163 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001164 }
1165 }
1166
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001167 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -07001168 for (size_t i = static_cast<size_t>(last_gc) + 1;
1169 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001170 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -07001171 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001172 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001173 case collector::kGcTypeSticky: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001174 const size_t alloc_space_size = non_moving_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001175 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
Mathieu Chartier590fee92013-09-13 13:46:47 -07001176 non_moving_space_->Capacity() - alloc_space_size >=
1177 min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001178 break;
1179 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001180 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001181 run_gc = have_zygote_space_;
1182 break;
Ian Rogers1d54e732013-05-02 21:10:01 -07001183 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001184 run_gc = true;
1185 break;
1186 default:
Mathieu Chartier590fee92013-09-13 13:46:47 -07001187 LOG(FATAL) << "Invalid GC type";
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001188 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001189
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001190 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001191 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -07001192 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001193 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001194 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001195
1196 // Did we free sufficient memory for the allocation to succeed?
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001197 ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001198 if (ptr != NULL) {
1199 return ptr;
1200 }
1201 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001202 }
1203
1204 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001205 // Try harder, growing the heap if necessary.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001206 ptr = TryToAllocateInstrumented(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001207 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001208 return ptr;
1209 }
1210
Elliott Hughes81ff3182012-03-23 20:35:56 -07001211 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1212 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1213 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001214
Mathieu Chartier590fee92013-09-13 13:46:47 -07001215 // TODO: Run finalization, but this can cause more allocations to occur.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001216 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1217 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001218
Mathieu Chartier590fee92013-09-13 13:46:47 -07001219 // We don't need a WaitForGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -07001220 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001221 return TryToAllocateInstrumented(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001222}
1223
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001224void Heap::SetTargetHeapUtilization(float target) {
1225 DCHECK_GT(target, 0.0f); // asserted in Java code
1226 DCHECK_LT(target, 1.0f);
1227 target_utilization_ = target;
1228}
1229
Ian Rogers1d54e732013-05-02 21:10:01 -07001230size_t Heap::GetObjectsAllocated() const {
1231 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001232 for (space::AllocSpace* space : alloc_spaces_) {
1233 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001234 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001235 return total;
1236}
1237
Ian Rogers1d54e732013-05-02 21:10:01 -07001238size_t Heap::GetObjectsAllocatedEver() const {
1239 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001240 for (space::AllocSpace* space : alloc_spaces_) {
1241 total += space->GetTotalObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001242 }
1243 return total;
1244}
1245
1246size_t Heap::GetBytesAllocatedEver() const {
1247 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001248 for (space::AllocSpace* space : alloc_spaces_) {
1249 total += space->GetTotalBytesAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001250 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001251 return total;
1252}
1253
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001254class InstanceCounter {
1255 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001256 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001257 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001258 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001259 }
1260
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001261 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001262 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001263 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001264 if (use_is_assignable_from_) {
1265 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
1266 ++counts_[i];
1267 }
1268 } else {
1269 if (instance_class == classes_[i]) {
1270 ++counts_[i];
1271 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001272 }
1273 }
1274 }
1275
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001276 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001277 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001278 bool use_is_assignable_from_;
1279 uint64_t* const counts_;
1280
1281 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001282};
1283
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001284void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001285 uint64_t* counts) {
1286 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1287 // is empty, so the live bitmap is the only place we need to look.
1288 Thread* self = Thread::Current();
1289 self->TransitionFromRunnableToSuspended(kNative);
1290 CollectGarbage(false);
1291 self->TransitionFromSuspendedToRunnable();
1292
1293 InstanceCounter counter(classes, use_is_assignable_from, counts);
1294 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001295 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001296}
1297
Elliott Hughes3b78c942013-01-15 17:35:41 -08001298class InstanceCollector {
1299 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001300 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001301 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1302 : class_(c), max_count_(max_count), instances_(instances) {
1303 }
1304
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001305 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1306 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001307 if (instance_class == class_) {
1308 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001309 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001310 }
1311 }
1312 }
1313
1314 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001315 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001316 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001317 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001318
1319 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1320};
1321
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001322void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1323 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001324 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1325 // is empty, so the live bitmap is the only place we need to look.
1326 Thread* self = Thread::Current();
1327 self->TransitionFromRunnableToSuspended(kNative);
1328 CollectGarbage(false);
1329 self->TransitionFromSuspendedToRunnable();
1330
1331 InstanceCollector collector(c, max_count, instances);
1332 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1333 GetLiveBitmap()->Visit(collector);
1334}
1335
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001336class ReferringObjectsFinder {
1337 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001338 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1339 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001340 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1341 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1342 }
1343
1344 // For bitmap Visit.
1345 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1346 // annotalysis on visitors.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001347 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
1348 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(o), *this, true);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001349 }
1350
1351 // For MarkSweep::VisitObjectReferences.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001352 void operator()(mirror::Object* referrer, mirror::Object* object,
Brian Carlstromdf629502013-07-17 22:39:56 -07001353 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001354 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001355 referring_objects_.push_back(referrer);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001356 }
1357 }
1358
1359 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001360 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001361 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001362 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001363
1364 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1365};
1366
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001367void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1368 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001369 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1370 // is empty, so the live bitmap is the only place we need to look.
1371 Thread* self = Thread::Current();
1372 self->TransitionFromRunnableToSuspended(kNative);
1373 CollectGarbage(false);
1374 self->TransitionFromSuspendedToRunnable();
1375
1376 ReferringObjectsFinder finder(o, max_count, referring_objects);
1377 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1378 GetLiveBitmap()->Visit(finder);
1379}
1380
Ian Rogers30fab402012-01-23 15:43:46 -08001381void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001382 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1383 // last GC will not have necessarily been cleared.
Ian Rogers1d54e732013-05-02 21:10:01 -07001384 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001385}
1386
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001387void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001388 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -07001389 Thread* self = Thread::Current();
1390 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001391 // Try to see if we have any Zygote spaces.
1392 if (have_zygote_space_) {
1393 return;
1394 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001395 VLOG(heap) << "Starting PreZygoteFork";
1396 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1397 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
1398 // Trim the pages at the end of the non moving space.
1399 non_moving_space_->Trim();
1400 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1401 // Create a new bump pointer space which we will compact into.
1402 if (semi_space_collector_ != nullptr) {
1403 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1404 non_moving_space_->Limit());
1405 // Compact the bump pointer space to a new zygote bump pointer space.
1406 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1407 Compact(&target_space, bump_pointer_space_);
1408 CHECK_EQ(temp_space_->GetBytesAllocated(), 0U);
1409 total_objects_freed_ever_ += semi_space_collector_->GetFreedObjects();
1410 total_bytes_freed_ever_ += semi_space_collector_->GetFreedBytes();
1411 // Update the end and write out image.
1412 non_moving_space_->SetEnd(target_space.End());
1413 non_moving_space_->SetLimit(target_space.Limit());
1414 accounting::SpaceBitmap* bitmap = non_moving_space_->GetLiveBitmap();
1415 // Record the allocations in the bitmap.
1416 VLOG(heap) << "Recording zygote allocations";
1417 mirror::Object* obj = reinterpret_cast<mirror::Object*>(target_space.Begin());
1418 const mirror::Object* end = reinterpret_cast<const mirror::Object*>(target_space.End());
1419 while (obj < end) {
1420 bitmap->Set(obj);
1421 obj = space::BumpPointerSpace::GetNextObject(obj);
1422 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001423 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001424 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
1425 // the remaining available heap memory.
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001426 space::MallocSpace* zygote_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001427 non_moving_space_ = zygote_space->CreateZygoteSpace("alloc space");
1428 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -07001429 // Change the GC retention policy of the zygote space to only collect when full.
1430 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001431 AddSpace(non_moving_space_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001432 have_zygote_space_ = true;
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001433 zygote_space->InvalidateAllocator();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001434 // Create the zygote space mod union table.
1435 accounting::ModUnionTable* mod_union_table =
1436 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1437 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1438 AddModUnionTable(mod_union_table);
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001439 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001440 for (const auto& collector : garbage_collectors_) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001441 collector->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001442 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001443}
1444
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001445void Heap::FlushAllocStack() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001446 MarkAllocStack(non_moving_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001447 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001448 allocation_stack_->Reset();
1449}
1450
Ian Rogers1d54e732013-05-02 21:10:01 -07001451void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1452 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001453 mirror::Object** limit = stack->End();
1454 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1455 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001456 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001457 if (LIKELY(bitmap->HasAddress(obj))) {
1458 bitmap->Set(obj);
1459 } else {
1460 large_objects->Set(obj);
1461 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001462 }
1463}
1464
Mathieu Chartier590fee92013-09-13 13:46:47 -07001465const char* PrettyCause(GcCause cause) {
1466 switch (cause) {
1467 case kGcCauseForAlloc: return "Alloc";
1468 case kGcCauseBackground: return "Background";
1469 case kGcCauseExplicit: return "Explicit";
1470 default:
1471 LOG(FATAL) << "Unreachable";
1472 }
1473 return "";
1474}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001475
Mathieu Chartier590fee92013-09-13 13:46:47 -07001476void Heap::SwapSemiSpaces() {
1477 // Swap the spaces so we allocate into the space which we just evacuated.
1478 std::swap(bump_pointer_space_, temp_space_);
1479}
1480
1481void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
1482 space::ContinuousMemMapAllocSpace* source_space) {
1483 CHECK(kMovingCollector);
1484 CHECK_NE(target_space, source_space) << "In-place compaction unsupported";
1485 if (target_space != source_space) {
1486 semi_space_collector_->SetFromSpace(source_space);
1487 semi_space_collector_->SetToSpace(target_space);
1488 semi_space_collector_->Run(false);
1489 }
1490}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001491
Ian Rogers1d54e732013-05-02 21:10:01 -07001492collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1493 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001494 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001495 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001496 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001497 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001498 if (self->IsHandlingStackOverflow()) {
1499 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1500 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001501 {
1502 gc_complete_lock_->AssertNotHeld(self);
1503 MutexLock mu(self, *gc_complete_lock_);
1504 // Ensure there is only one GC at a time.
1505 WaitForGcToCompleteLocked(self);
1506 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1507 // Not doing at the moment to ensure soft references are cleared.
1508 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
1509 if (gc_disable_count_ != 0) {
1510 LOG(WARNING) << "Skipping GC due to disable count " << gc_disable_count_;
1511 return collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001512 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001513 is_gc_running_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001514 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001515
Mathieu Chartier590fee92013-09-13 13:46:47 -07001516 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
1517 ++runtime->GetStats()->gc_for_alloc_count;
1518 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001519 }
1520
Ian Rogers1d54e732013-05-02 21:10:01 -07001521 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001522 uint64_t gc_start_size = GetBytesAllocated();
1523 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001524 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001525 // Back to back GCs can cause 0 ms of wait time in between GC invocations.
1526 if (LIKELY(ms_delta != 0)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001527 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001528 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1529 }
1530
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001531 if (gc_type == collector::kGcTypeSticky &&
Mathieu Chartier590fee92013-09-13 13:46:47 -07001532 non_moving_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001533 gc_type = collector::kGcTypePartial;
1534 }
1535
Ian Rogers1d54e732013-05-02 21:10:01 -07001536 DCHECK_LT(gc_type, collector::kGcTypeMax);
1537 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001538
Mathieu Chartier590fee92013-09-13 13:46:47 -07001539 collector::GarbageCollector* collector = nullptr;
1540 if (kMovingCollector) {
1541 gc_type = semi_space_collector_->GetGcType();
1542 CHECK_EQ(temp_space_->GetObjectsAllocated(), 0U);
1543 semi_space_collector_->SetFromSpace(bump_pointer_space_);
1544 semi_space_collector_->SetToSpace(temp_space_);
1545 mprotect(temp_space_->Begin(), temp_space_->Capacity(), PROT_READ | PROT_WRITE);
1546 }
1547 for (const auto& cur_collector : garbage_collectors_) {
1548 if (cur_collector->IsConcurrent() == concurrent_gc_ &&
1549 cur_collector->GetGcType() == gc_type) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001550 collector = cur_collector;
1551 break;
1552 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001553 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001554 if (kMovingCollector) {
1555 gc_type = collector::kGcTypeFull;
1556 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001557 CHECK(collector != NULL)
1558 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1559 << " and type=" << gc_type;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001560
Mathieu Chartier590fee92013-09-13 13:46:47 -07001561 ATRACE_BEGIN(StringPrintf("%s %s GC", PrettyCause(gc_cause), collector->GetName()).c_str());
1562
1563 collector->Run(clear_soft_references);
Ian Rogers1d54e732013-05-02 21:10:01 -07001564 total_objects_freed_ever_ += collector->GetFreedObjects();
1565 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001566
Mathieu Chartier39e32612013-11-12 16:28:05 -08001567 // Enqueue cleared references.
1568 EnqueueClearedReferences();
1569
Mathieu Chartier590fee92013-09-13 13:46:47 -07001570 // Grow the heap so that we know when to perform the next GC.
1571 GrowForUtilization(gc_type, collector->GetDurationNs());
1572
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001573 if (care_about_pause_times_) {
1574 const size_t duration = collector->GetDurationNs();
1575 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1576 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001577 bool was_slow = duration > long_gc_log_threshold_ ||
1578 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001579 if (!was_slow) {
1580 for (uint64_t pause : pauses) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001581 was_slow = was_slow || pause > long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001582 }
1583 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001584 if (was_slow) {
1585 const size_t percent_free = GetPercentFree();
1586 const size_t current_heap_size = GetBytesAllocated();
1587 const size_t total_memory = GetTotalMemory();
1588 std::ostringstream pause_string;
1589 for (size_t i = 0; i < pauses.size(); ++i) {
1590 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1591 << ((i != pauses.size() - 1) ? ", " : "");
1592 }
1593 LOG(INFO) << gc_cause << " " << collector->GetName()
1594 << " GC freed " << collector->GetFreedObjects() << "("
1595 << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1596 << collector->GetFreedLargeObjects() << "("
1597 << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1598 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1599 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1600 << " total " << PrettyDuration((duration / 1000) * 1000);
1601 if (VLOG_IS_ON(heap)) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001602 LOG(INFO) << Dumpable<TimingLogger>(collector->GetTimings());
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001603 }
1604 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001605 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001606
Ian Rogers15bf2d32012-08-28 17:33:04 -07001607 {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001608 MutexLock mu(self, *gc_complete_lock_);
1609 is_gc_running_ = false;
1610 last_gc_type_ = gc_type;
1611 // Wake anyone who may have been waiting for the GC to complete.
1612 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001613 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001614
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001615 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001616
1617 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001618 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001619 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001620}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001621
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001622static mirror::Object* RootMatchesObjectVisitor(mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001623 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001624 if (root == obj) {
1625 LOG(INFO) << "Object " << obj << " is a root";
1626 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001627 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001628}
1629
1630class ScanVisitor {
1631 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001632 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001633 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001634 }
1635};
1636
Ian Rogers1d54e732013-05-02 21:10:01 -07001637// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001638class VerifyReferenceVisitor {
1639 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001640 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001641 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001642 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001643
1644 bool Failed() const {
1645 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001646 }
1647
1648 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001649 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001650 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1651 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001652 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001653 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001654 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1655 accounting::CardTable* card_table = heap_->GetCardTable();
1656 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1657 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001658 if (!failed_) {
1659 // Print message on only on first failure to prevent spam.
1660 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
1661 failed_ = true;
1662 }
1663 if (obj != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001664 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001665 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
1666 << offset << "\n card value = " << static_cast<int>(*card_addr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001667 if (heap_->IsValidObjectAddress(obj->GetClass())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001668 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1669 } else {
1670 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
1671 }
1672
1673 // Attmept to find the class inside of the recently freed objects.
1674 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001675 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
1676 space::MallocSpace* space = ref_space->AsMallocSpace();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001677 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
1678 if (ref_class != nullptr) {
1679 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
1680 << PrettyClass(ref_class);
1681 } else {
1682 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
1683 }
1684 }
1685
Mathieu Chartier590fee92013-09-13 13:46:47 -07001686 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001687 ref->GetClass()->IsClass()) {
1688 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1689 } else {
1690 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
1691 << ") is not a valid heap address";
1692 }
1693
Ian Rogers1d54e732013-05-02 21:10:01 -07001694 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1695 void* cover_begin = card_table->AddrFromCard(card_addr);
1696 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1697 accounting::CardTable::kCardSize);
1698 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1699 << "-" << cover_end;
1700 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001701
Ian Rogers1d54e732013-05-02 21:10:01 -07001702 // Print out how the object is live.
1703 if (bitmap != NULL && bitmap->Test(obj)) {
1704 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1705 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001706 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001707 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1708 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001709 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001710 LOG(ERROR) << "Object " << obj << " found in live stack";
1711 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001712 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1713 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
1714 }
1715 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1716 LOG(ERROR) << "Ref " << ref << " found in live stack";
1717 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001718 // Attempt to see if the card table missed the reference.
1719 ScanVisitor scan_visitor;
1720 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1721 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001722 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001723
1724 // Search to see if any of the roots reference our object.
1725 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1726 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1727
1728 // Search to see if any of the roots reference our reference.
1729 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1730 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1731 } else {
1732 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001733 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001734 }
1735 }
1736
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001737 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001738 return heap_->IsLiveObjectLocked(obj, true, false, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001739 }
1740
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001741 static mirror::Object* VerifyRoots(mirror::Object* root, void* arg) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001742 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001743 (*visitor)(nullptr, root, MemberOffset(0), true);
1744 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001745 }
1746
1747 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001748 Heap* const heap_;
1749 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001750};
1751
Ian Rogers1d54e732013-05-02 21:10:01 -07001752// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001753class VerifyObjectVisitor {
1754 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001755 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001756
Mathieu Chartier590fee92013-09-13 13:46:47 -07001757 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001758 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001759 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1760 // be live or else how did we find it in the live bitmap?
1761 VerifyReferenceVisitor visitor(heap_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001762 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001763 collector::MarkSweep::VisitObjectReferences(obj, visitor, true);
1764 if (obj->GetClass()->IsReferenceClass()) {
1765 visitor(obj, heap_->GetReferenceReferent(obj), MemberOffset(0), false);
1766 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001767 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001768 }
1769
Mathieu Chartier590fee92013-09-13 13:46:47 -07001770 static void VisitCallback(mirror::Object* obj, void* arg)
1771 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1772 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
1773 visitor->operator()(obj);
1774 }
1775
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001776 bool Failed() const {
1777 return failed_;
1778 }
1779
1780 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001781 Heap* const heap_;
1782 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001783};
1784
1785// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001786bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001787 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001788 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001789 allocation_stack_->Sort();
1790 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001791 VerifyObjectVisitor visitor(this);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001792 // Verify objects in the allocation stack since these will be objects which were:
1793 // 1. Allocated prior to the GC (pre GC verification).
1794 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001795 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001796 // pointing to dead objects if they are not reachable.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001797 VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
1798 // Verify the roots:
1799 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001800 if (visitor.Failed()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001801 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001802 for (const auto& table_pair : mod_union_tables_) {
1803 accounting::ModUnionTable* mod_union_table = table_pair.second;
1804 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
1805 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001806 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001807 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001808 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001809 return true;
1810}
1811
1812class VerifyReferenceCardVisitor {
1813 public:
1814 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1815 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1816 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001817 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001818 }
1819
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001820 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1821 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001822 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1823 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001824 // Filter out class references since changing an object's class does not mark the card as dirty.
1825 // Also handles large objects, since the only reference they hold is a class reference.
1826 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001827 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001828 // If the object is not dirty and it is referencing something in the live stack other than
1829 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001830 if (!card_table->AddrIsInCardTable(obj)) {
1831 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1832 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001833 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001834 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1835 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001836 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001837 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1838 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001839 LOG(ERROR) << "Object " << obj << " found in live stack";
1840 }
1841 if (heap_->GetLiveBitmap()->Test(obj)) {
1842 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1843 }
1844 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1845 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1846
1847 // Print which field of the object is dead.
1848 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001849 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001850 CHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001851 const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
1852 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001853 CHECK(fields != NULL);
1854 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001855 const mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001856 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1857 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1858 << PrettyField(cur);
1859 break;
1860 }
1861 }
1862 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001863 const mirror::ObjectArray<mirror::Object>* object_array =
1864 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001865 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1866 if (object_array->Get(i) == ref) {
1867 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1868 }
1869 }
1870 }
1871
1872 *failed_ = true;
1873 }
1874 }
1875 }
1876 }
1877
1878 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001879 Heap* const heap_;
1880 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001881};
1882
1883class VerifyLiveStackReferences {
1884 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001885 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001886 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001887 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001888
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001889 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001890 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1891 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001892 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(obj), visitor, true);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001893 }
1894
1895 bool Failed() const {
1896 return failed_;
1897 }
1898
1899 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001900 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001901 bool failed_;
1902};
1903
1904bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001905 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001906
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001907 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001908 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001909 VerifyLiveStackReferences visitor(this);
1910 GetLiveBitmap()->Visit(visitor);
1911
1912 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001913 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001914 visitor(*it);
1915 }
1916
1917 if (visitor.Failed()) {
1918 DumpSpaces();
1919 return false;
1920 }
1921 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001922}
1923
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001924void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001925 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001926}
1927
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001928accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
1929 auto it = mod_union_tables_.find(space);
1930 if (it == mod_union_tables_.end()) {
1931 return nullptr;
1932 }
1933 return it->second;
1934}
1935
Ian Rogers5fe9af72013-11-14 00:17:20 -08001936void Heap::ProcessCards(TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001937 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001938 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001939 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
1940 if (table != nullptr) {
1941 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
1942 "ImageModUnionClearCards";
Ian Rogers5fe9af72013-11-14 00:17:20 -08001943 TimingLogger::ScopedSplit split(name, &timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001944 table->ClearCards();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001945 } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001946 TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001947 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1948 // were dirty before the GC started.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001949 // TODO: Don't need to use atomic.
1950 // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
1951 // roots and then we scan / update mod union tables after. We will always scan either card.//
1952 // If we end up with the non aged card, we scan it it in the pause.
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001953 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001954 }
1955 }
1956}
1957
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001958static mirror::Object* IdentityCallback(mirror::Object* obj, void*) {
1959 return obj;
1960}
1961
Ian Rogers1d54e732013-05-02 21:10:01 -07001962void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001963 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1964 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001965
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001966 if (verify_pre_gc_heap_) {
1967 thread_list->SuspendAll();
1968 {
1969 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1970 if (!VerifyHeapReferences()) {
1971 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1972 }
1973 }
1974 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001975 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001976
1977 // Check that all objects which reference things in the live stack are on dirty cards.
1978 if (verify_missing_card_marks_) {
1979 thread_list->SuspendAll();
1980 {
1981 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1982 SwapStacks();
1983 // Sort the live stack so that we can quickly binary search it later.
1984 if (!VerifyMissingCardMarks()) {
1985 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1986 }
1987 SwapStacks();
1988 }
1989 thread_list->ResumeAll();
1990 }
1991
1992 if (verify_mod_union_table_) {
1993 thread_list->SuspendAll();
1994 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001995 for (const auto& table_pair : mod_union_tables_) {
1996 accounting::ModUnionTable* mod_union_table = table_pair.second;
1997 mod_union_table->UpdateAndMarkReferences(IdentityCallback, nullptr);
1998 mod_union_table->Verify();
1999 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002000 thread_list->ResumeAll();
2001 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002002}
2003
Ian Rogers1d54e732013-05-02 21:10:01 -07002004void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002005 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
2006 // reachable objects.
2007 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002008 Thread* self = Thread::Current();
2009 CHECK_NE(self->GetState(), kRunnable);
Ian Rogers1d54e732013-05-02 21:10:01 -07002010 {
2011 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2012 // Swapping bound bitmaps does nothing.
2013 gc->SwapBitmaps();
2014 if (!VerifyHeapReferences()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002015 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
Ian Rogers1d54e732013-05-02 21:10:01 -07002016 }
2017 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002018 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002019 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002020}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002021
Ian Rogers1d54e732013-05-02 21:10:01 -07002022void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002023 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002024 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002025 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07002026 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002027 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002028 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07002029}
2030
Mathieu Chartier590fee92013-09-13 13:46:47 -07002031collector::GcType Heap::WaitForGcToComplete(Thread* self) {
2032 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
2033 MutexLock mu(self, *gc_complete_lock_);
2034 return WaitForGcToCompleteLocked(self);
2035}
2036
2037collector::GcType Heap::WaitForGcToCompleteLocked(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002038 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002039 uint64_t wait_start = NanoTime();
2040 while (is_gc_running_) {
2041 ATRACE_BEGIN("GC: Wait For Completion");
2042 // We must wait, change thread state then sleep on gc_complete_cond_;
2043 gc_complete_cond_->Wait(self);
2044 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07002045 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002046 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002047 uint64_t wait_time = NanoTime() - wait_start;
2048 total_wait_time_ += wait_time;
2049 if (wait_time > long_pause_log_threshold_) {
2050 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time);
2051 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07002052 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07002053}
2054
Elliott Hughesc967f782012-04-16 10:23:15 -07002055void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002056 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002057 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07002058 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07002059}
2060
2061size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002062 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07002063}
2064
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002065void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002066 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002067 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002068 << PrettySize(GetMaxMemory());
2069 max_allowed_footprint = GetMaxMemory();
2070 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07002071 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07002072}
2073
Mathieu Chartier590fee92013-09-13 13:46:47 -07002074bool Heap::IsMovableObject(const mirror::Object* obj) const {
2075 if (kMovingCollector) {
2076 DCHECK(!IsInTempSpace(obj));
2077 if (bump_pointer_space_->HasAddress(obj)) {
2078 return true;
2079 }
2080 }
2081 return false;
2082}
2083
2084bool Heap::IsInTempSpace(const mirror::Object* obj) const {
2085 if (temp_space_->HasAddress(obj) && !temp_space_->Contains(obj)) {
2086 return true;
2087 }
2088 return false;
2089}
2090
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002091void Heap::UpdateMaxNativeFootprint() {
2092 size_t native_size = native_bytes_allocated_;
2093 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
2094 size_t target_size = native_size / GetTargetHeapUtilization();
2095 if (target_size > native_size + max_free_) {
2096 target_size = native_size + max_free_;
2097 } else if (target_size < native_size + min_free_) {
2098 target_size = native_size + min_free_;
2099 }
2100 native_footprint_gc_watermark_ = target_size;
2101 native_footprint_limit_ = 2 * target_size - native_size;
2102}
2103
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002104void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002105 // We know what our utilization is at this moment.
2106 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08002107 const size_t bytes_allocated = GetBytesAllocated();
2108 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07002109 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002110
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002111 size_t target_size;
2112 if (gc_type != collector::kGcTypeSticky) {
2113 // Grow the heap for non sticky GC.
2114 target_size = bytes_allocated / GetTargetHeapUtilization();
2115 if (target_size > bytes_allocated + max_free_) {
2116 target_size = bytes_allocated + max_free_;
2117 } else if (target_size < bytes_allocated + min_free_) {
2118 target_size = bytes_allocated + min_free_;
2119 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002120 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002121 next_gc_type_ = collector::kGcTypeSticky;
2122 } else {
2123 // Based on how close the current heap size is to the target size, decide
2124 // whether or not to do a partial or sticky GC next.
2125 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
2126 next_gc_type_ = collector::kGcTypeSticky;
2127 } else {
2128 next_gc_type_ = collector::kGcTypePartial;
2129 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002130
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002131 // If we have freed enough memory, shrink the heap back down.
2132 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
2133 target_size = bytes_allocated + max_free_;
2134 } else {
2135 target_size = std::max(bytes_allocated, max_allowed_footprint_);
2136 }
2137 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002138
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002139 if (!ignore_max_footprint_) {
2140 SetIdealFootprint(target_size);
2141
2142 if (concurrent_gc_) {
2143 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002144 // Calculate the estimated GC duration.
2145 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
2146 // Estimate how many remaining bytes we will have when we need to start the next GC.
2147 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
2148 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
2149 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
2150 // A never going to happen situation that from the estimated allocation rate we will exceed
2151 // the applications entire footprint with the given estimated allocation rate. Schedule
2152 // another GC straight away.
2153 concurrent_start_bytes_ = bytes_allocated;
2154 } else {
2155 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
2156 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
2157 // right away.
2158 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
2159 }
2160 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
2161 DCHECK_LE(max_allowed_footprint_, growth_limit_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08002162 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002163 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07002164}
2165
jeffhaoc1160702011-10-27 15:48:45 -07002166void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08002167 growth_limit_ = capacity_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002168 non_moving_space_->ClearGrowthLimit();
jeffhaoc1160702011-10-27 15:48:45 -07002169}
2170
Elliott Hughesadb460d2011-10-05 17:02:34 -07002171void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002172 MemberOffset reference_queue_offset,
2173 MemberOffset reference_queueNext_offset,
2174 MemberOffset reference_pendingNext_offset,
2175 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002176 reference_referent_offset_ = reference_referent_offset;
2177 reference_queue_offset_ = reference_queue_offset;
2178 reference_queueNext_offset_ = reference_queueNext_offset;
2179 reference_pendingNext_offset_ = reference_pendingNext_offset;
2180 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
2181 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
2182 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
2183 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
2184 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
2185 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
2186}
2187
Mathieu Chartier590fee92013-09-13 13:46:47 -07002188void Heap::SetReferenceReferent(mirror::Object* reference, mirror::Object* referent) {
2189 DCHECK(reference != NULL);
2190 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
2191 reference->SetFieldObject(reference_referent_offset_, referent, true);
2192}
2193
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002194mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002195 DCHECK(reference != NULL);
2196 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002197 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002198}
2199
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002200void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002201 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08002202 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08002203 ArgArray arg_array(NULL, 0);
2204 arg_array.Append(reinterpret_cast<uint32_t>(object));
2205 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07002206 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002207}
2208
Mathieu Chartier590fee92013-09-13 13:46:47 -07002209void Heap::PrintReferenceQueue(std::ostream& os, mirror::Object** queue) {
2210 os << "Refernece queue " << queue << "\n";
2211 if (queue != nullptr) {
2212 mirror::Object* list = *queue;
2213 if (list != nullptr) {
2214 mirror::Object* cur = list;
2215 do {
2216 mirror::Object* pending_next =
2217 cur->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
2218 os << "PendingNext=" << pending_next;
2219 if (cur->GetClass()->IsFinalizerReferenceClass()) {
2220 os << " Zombie=" <<
2221 cur->GetFieldObject<mirror::Object*>(finalizer_reference_zombie_offset_, false);
2222 }
2223 os << "\n";
2224 cur = pending_next;
2225 } while (cur != list);
2226 }
2227 }
2228}
2229
Mathieu Chartier39e32612013-11-12 16:28:05 -08002230void Heap::EnqueueClearedReferences() {
2231 if (!cleared_references_.IsEmpty()) {
Ian Rogers64b6d142012-10-29 16:34:15 -07002232 // When a runtime isn't started there are no reference queues to care about so ignore.
2233 if (LIKELY(Runtime::Current()->IsStarted())) {
2234 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08002235 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08002236 ArgArray arg_array(NULL, 0);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002237 arg_array.Append(reinterpret_cast<uint32_t>(cleared_references_.GetList()));
Jeff Hao5d917302013-02-27 17:57:33 -08002238 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07002239 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07002240 }
Mathieu Chartier39e32612013-11-12 16:28:05 -08002241 cleared_references_.Clear();
Elliott Hughesadb460d2011-10-05 17:02:34 -07002242 }
2243}
2244
Ian Rogers1f539342012-10-03 21:09:42 -07002245void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07002246 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07002247 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08002248 DCHECK(concurrent_gc_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002249 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
2250 self->IsHandlingStackOverflow()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002251 return;
2252 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002253 // We already have a request pending, no reason to start more until we update
2254 // concurrent_start_bytes_.
2255 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers120f1c72012-09-28 17:17:10 -07002256 JNIEnv* env = self->GetJniEnv();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002257 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2258 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002259 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2260 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002261 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002262}
2263
Ian Rogers81d425b2012-09-27 16:03:43 -07002264void Heap::ConcurrentGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002265 if (Runtime::Current()->IsShuttingDown(self)) {
2266 return;
Mathieu Chartier2542d662012-06-21 17:14:11 -07002267 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002268 // Wait for any GCs currently running to finish.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002269 if (WaitForGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002270 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002271 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002272}
2273
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002274void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08002275 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
2276 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
2277 // a space it will hold its lock and can become a cause of jank.
2278 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
2279 // forking.
2280
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002281 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2282 // because that only marks object heads, so a large array looks like lots of empty space. We
2283 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2284 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2285 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2286 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08002287 uint64_t ms_time = MilliTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002288 // Don't bother trimming the alloc space if a heap trim occurred in the last two seconds.
2289 if (ms_time - last_trim_time_ms_ < 2 * 1000) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002290 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002291 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002292
2293 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002294 Runtime* runtime = Runtime::Current();
2295 if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self)) {
2296 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2297 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2298 // as we don't hold the lock while requesting the trim).
2299 return;
Ian Rogerse1d490c2012-02-03 09:09:07 -08002300 }
Ian Rogers48931882013-01-22 14:35:16 -08002301
Ian Rogers1d54e732013-05-02 21:10:01 -07002302 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002303 ListenForProcessStateChange();
2304
2305 // Trim only if we do not currently care about pause times.
2306 if (!care_about_pause_times_) {
2307 JNIEnv* env = self->GetJniEnv();
2308 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2309 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2310 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2311 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2312 CHECK(!env->ExceptionCheck());
2313 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002314}
2315
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002316void Heap::RevokeThreadLocalBuffers(Thread* thread) {
2317 non_moving_space_->RevokeThreadLocalBuffers(thread);
2318}
2319
2320void Heap::RevokeAllThreadLocalBuffers() {
2321 non_moving_space_->RevokeAllThreadLocalBuffers();
2322}
2323
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002324bool Heap::IsGCRequestPending() const {
2325 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2326}
2327
Mathieu Chartier590fee92013-09-13 13:46:47 -07002328void Heap::RunFinalization(JNIEnv* env) {
2329 // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
2330 if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
2331 CHECK(WellKnownClasses::java_lang_System != nullptr);
2332 WellKnownClasses::java_lang_System_runFinalization =
2333 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2334 CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
2335 }
2336 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2337 WellKnownClasses::java_lang_System_runFinalization);
2338}
2339
Ian Rogers1eb512d2013-10-18 15:42:20 -07002340void Heap::RegisterNativeAllocation(JNIEnv* env, int bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002341 Thread* self = ThreadForEnv(env);
2342 if (native_need_to_run_finalization_) {
2343 RunFinalization(env);
2344 UpdateMaxNativeFootprint();
2345 native_need_to_run_finalization_ = false;
2346 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002347 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002348 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002349 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
2350 // The second watermark is higher than the gc watermark. If you hit this it means you are
2351 // allocating native objects faster than the GC can keep up with.
2352 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002353 if (WaitForGcToComplete(self) != collector::kGcTypeNone) {
2354 // Just finished a GC, attempt to run finalizers.
2355 RunFinalization(env);
2356 CHECK(!env->ExceptionCheck());
2357 }
2358 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2359 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2360 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
2361 RunFinalization(env);
2362 native_need_to_run_finalization_ = false;
2363 CHECK(!env->ExceptionCheck());
2364 }
2365 // We have just run finalizers, update the native watermark since it is very likely that
2366 // finalizers released native managed allocations.
2367 UpdateMaxNativeFootprint();
2368 } else if (!IsGCRequestPending()) {
2369 if (concurrent_gc_) {
2370 RequestConcurrentGC(self);
2371 } else {
2372 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002373 }
2374 }
2375 }
2376}
2377
Ian Rogers1eb512d2013-10-18 15:42:20 -07002378void Heap::RegisterNativeFree(JNIEnv* env, int bytes) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002379 int expected_size, new_size;
2380 do {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002381 expected_size = native_bytes_allocated_.load();
2382 new_size = expected_size - bytes;
2383 if (UNLIKELY(new_size < 0)) {
2384 ScopedObjectAccess soa(env);
2385 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
2386 StringPrintf("Attempted to free %d native bytes with only %d native bytes "
2387 "registered as allocated", bytes, expected_size).c_str());
2388 break;
2389 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002390 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002391}
2392
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002393int64_t Heap::GetTotalMemory() const {
2394 int64_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002395 for (const auto& space : continuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002396 // Currently don't include the image space.
2397 if (!space->IsImageSpace()) {
2398 ret += space->Size();
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002399 }
2400 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002401 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002402 if (space->IsLargeObjectSpace()) {
2403 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2404 }
2405 }
2406 return ret;
2407}
2408
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002409void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
2410 DCHECK(mod_union_table != nullptr);
2411 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
2412}
2413
Ian Rogers1d54e732013-05-02 21:10:01 -07002414} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002415} // namespace art