blob: f446fcf541b22c7d8794604059ca4eb0bd13d843 [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"
44#include "gc/space/space-inl.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070045#include "heap-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070046#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080047#include "invoke_arg_array_builder.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070048#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080049#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "mirror/object.h"
51#include "mirror/object-inl.h"
52#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080053#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080054#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070055#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070056#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070057#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070058#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070059#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070060#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070061
62namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070063namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070064
Mathieu Chartier720ef762013-08-17 14:46:54 -070065static constexpr bool kGCALotMode = false;
66static constexpr size_t kGcAlotInterval = KB;
67static constexpr bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070068// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070069static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070070
Mathieu Chartier0051be62012-10-12 17:47:11 -070071Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Ian Rogers8d31bbd2013-10-13 10:44:14 -070072 double target_utilization, size_t capacity, const std::string& image_file_name,
Mathieu Chartier2775ee42013-08-20 17:43:47 -070073 bool concurrent_gc, size_t parallel_gc_threads, size_t conc_gc_threads,
74 bool low_memory_mode, size_t long_pause_log_threshold, size_t long_gc_log_threshold,
75 bool ignore_max_footprint)
Mathieu Chartier590fee92013-09-13 13:46:47 -070076 : non_moving_space_(NULL),
77 concurrent_gc_(!kMovingCollector && concurrent_gc),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070078 parallel_gc_threads_(parallel_gc_threads),
79 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070080 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070081 long_pause_log_threshold_(long_pause_log_threshold),
82 long_gc_log_threshold_(long_gc_log_threshold),
83 ignore_max_footprint_(ignore_max_footprint),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070084 have_zygote_space_(false),
Mathieu Chartier39e32612013-11-12 16:28:05 -080085 soft_reference_queue_(this),
86 weak_reference_queue_(this),
87 finalizer_reference_queue_(this),
88 phantom_reference_queue_(this),
89 cleared_references_(this),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080090 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070091 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070092 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080093 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070094 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070095 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070096 native_footprint_gc_watermark_(initial_size),
97 native_footprint_limit_(2 * initial_size),
Mathieu Chartier590fee92013-09-13 13:46:47 -070098 native_need_to_run_finalization_(false),
Mathieu Chartierc39e3422013-08-07 16:41:36 -070099 activity_thread_class_(NULL),
100 application_thread_class_(NULL),
101 activity_thread_(NULL),
102 application_thread_(NULL),
103 last_process_state_id_(NULL),
104 // Initially care about pauses in case we never get notified of process states, or if the JNI
105 // code becomes broken.
106 care_about_pause_times_(true),
Mathieu Chartier720ef762013-08-17 14:46:54 -0700107 concurrent_start_bytes_(concurrent_gc_ ? initial_size - kMinConcurrentRemainingBytes
108 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700109 total_bytes_freed_ever_(0),
110 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800111 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700112 native_bytes_allocated_(0),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700113 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700114 verify_missing_card_marks_(false),
115 verify_system_weaks_(false),
116 verify_pre_gc_heap_(false),
117 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700118 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700119 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700120 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700121 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800122 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700123 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
124 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
125 * verification is enabled, we limit the size of allocation stacks to speed up their
126 * searching.
127 */
128 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
Mathieu Chartier590fee92013-09-13 13:46:47 -0700129 : (kDesiredHeapVerification > kVerifyAllFast) ? KB : MB),
130 bump_pointer_space_(nullptr),
131 temp_space_(nullptr),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800132 reference_referent_offset_(0),
133 reference_queue_offset_(0),
134 reference_queueNext_offset_(0),
135 reference_pendingNext_offset_(0),
136 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700137 min_free_(min_free),
138 max_free_(max_free),
139 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700140 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700141 total_allocation_time_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700142 verify_object_mode_(kHeapVerificationNotPermitted),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700143 gc_disable_count_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700144 running_on_valgrind_(RUNNING_ON_VALGRIND) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800145 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800146 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700147 }
148
Ian Rogers1d54e732013-05-02 21:10:01 -0700149 live_bitmap_.reset(new accounting::HeapBitmap(this));
150 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700151
Ian Rogers30fab402012-01-23 15:43:46 -0800152 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700153 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800154 if (!image_file_name.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700155 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700156 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700157 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800158 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
159 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800160 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
161 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700162 if (oat_file_end_addr > requested_alloc_space_begin) {
163 requested_alloc_space_begin =
164 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
165 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700166 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700167 }
168
Mathieu Chartier590fee92013-09-13 13:46:47 -0700169 const char* name = Runtime::Current()->IsZygote() ? "zygote space" : "alloc space";
170 non_moving_space_ = space::DlMallocSpace::Create(name, initial_size, growth_limit, capacity,
171 requested_alloc_space_begin);
172
173 if (kMovingCollector) {
174 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
175 // TODO: Having 3+ spaces as big as the large heap size can cause virtual memory fragmentation
176 // issues.
177 const size_t bump_pointer_space_size = std::min(non_moving_space_->Capacity(), 128 * MB);
178 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space",
179 bump_pointer_space_size, nullptr);
180 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
181 AddSpace(bump_pointer_space_);
182 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2", bump_pointer_space_size,
183 nullptr);
184 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
185 AddSpace(temp_space_);
186 }
187
188 CHECK(non_moving_space_ != NULL) << "Failed to create non-moving space";
189 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
190 AddSpace(non_moving_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700191
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700192 // Allocate the large object space.
193 const bool kUseFreeListSpaceForLOS = false;
194 if (kUseFreeListSpaceForLOS) {
195 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
196 } else {
197 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
198 }
199 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700200 AddSpace(large_object_space_);
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700201
Ian Rogers1d54e732013-05-02 21:10:01 -0700202 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700203 CHECK(!continuous_spaces_.empty());
204 // Relies on the spaces being sorted.
Ian Rogers1d54e732013-05-02 21:10:01 -0700205 byte* heap_begin = continuous_spaces_.front()->Begin();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700206 byte* heap_end = continuous_spaces_.back()->Limit();
207 size_t heap_capacity = heap_end - heap_begin;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700208
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800209 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700210 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700211 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700212
Mathieu Chartier590fee92013-09-13 13:46:47 -0700213 // Card cache for now since it makes it easier for us to update the references to the copying
214 // spaces.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700215 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier590fee92013-09-13 13:46:47 -0700216 new accounting::ModUnionTableCardCache("Image mod-union table", this, GetImageSpace());
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700217 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
218 AddModUnionTable(mod_union_table);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700219
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700220 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700221 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700222
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800223 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700224 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700225 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
226 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
227 max_allocation_stack_size_));
228 live_stack_.reset(accounting::ObjectStack::Create("live stack",
229 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700230
Mathieu Chartier65db8802012-11-20 12:36:46 -0800231 // It's still too early to take a lock because there are no threads yet, but we can create locks
232 // now. We don't create it earlier to make it clear that you can't use locks during heap
233 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700234 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700235 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
236 *gc_complete_lock_));
Ian Rogers1d54e732013-05-02 21:10:01 -0700237 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800238 last_gc_size_ = GetBytesAllocated();
239
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700240 if (ignore_max_footprint_) {
241 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700242 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700243 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700244 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700245
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800246 // Create our garbage collectors.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700247 if (!kMovingCollector) {
248 for (size_t i = 0; i < 2; ++i) {
249 const bool concurrent = i != 0;
250 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
251 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
252 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
253 }
254 } else {
255 semi_space_collector_ = new collector::SemiSpace(this);
256 garbage_collectors_.push_back(semi_space_collector_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700257 }
258
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700259 if (running_on_valgrind_) {
Ian Rogersfa824272013-11-05 16:12:57 -0800260 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700261 }
262
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800263 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800264 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700265 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700266}
267
Mathieu Chartier590fee92013-09-13 13:46:47 -0700268bool Heap::IsCompilingBoot() const {
269 for (const auto& space : continuous_spaces_) {
270 if (space->IsImageSpace()) {
271 return false;
272 } else if (space->IsZygoteSpace()) {
273 return false;
274 }
275 }
276 return true;
277}
278
279bool Heap::HasImageSpace() const {
280 for (const auto& space : continuous_spaces_) {
281 if (space->IsImageSpace()) {
282 return true;
283 }
284 }
285 return false;
286}
287
288void Heap::IncrementDisableGC(Thread* self) {
289 // Need to do this holding the lock to prevent races where the GC is about to run / running when
290 // we attempt to disable it.
291 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
292 MutexLock mu(self, *gc_complete_lock_);
293 WaitForGcToCompleteLocked(self);
294 ++gc_disable_count_;
295}
296
297void Heap::DecrementDisableGC(Thread* self) {
298 MutexLock mu(self, *gc_complete_lock_);
299 CHECK_GE(gc_disable_count_, 0U);
300 --gc_disable_count_;
301}
302
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700303void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700304 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
305 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800306 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700307 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700308}
309
Mathieu Chartier590fee92013-09-13 13:46:47 -0700310void Heap::VisitObjects(ObjectVisitorCallback callback, void* arg) {
311 // Visit objects in bump pointer space.
312 Thread* self = Thread::Current();
313 // TODO: Use reference block.
314 std::vector<SirtRef<mirror::Object>*> saved_refs;
315 if (bump_pointer_space_ != nullptr) {
316 // Need to put all these in sirts since the callback may trigger a GC. TODO: Use a better data
317 // structure.
318 mirror::Object* obj = reinterpret_cast<mirror::Object*>(bump_pointer_space_->Begin());
319 const mirror::Object* end = reinterpret_cast<const mirror::Object*>(
320 bump_pointer_space_->End());
321 while (obj < end) {
322 saved_refs.push_back(new SirtRef<mirror::Object>(self, obj));
323 obj = space::BumpPointerSpace::GetNextObject(obj);
324 }
325 }
326 // TODO: Switch to standard begin and end to use ranged a based loop.
327 for (mirror::Object** it = allocation_stack_->Begin(), **end = allocation_stack_->End();
328 it < end; ++it) {
329 mirror::Object* obj = *it;
330 // Objects in the allocation stack might be in a movable space.
331 saved_refs.push_back(new SirtRef<mirror::Object>(self, obj));
332 }
333 GetLiveBitmap()->Walk(callback, arg);
334 for (const auto& ref : saved_refs) {
335 callback(ref->get(), arg);
336 }
337 // Need to free the sirts in reverse order they were allocated.
338 for (size_t i = saved_refs.size(); i != 0; --i) {
339 delete saved_refs[i - 1];
340 }
341}
342
343void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
344 MarkAllocStack(non_moving_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(), stack);
345}
346
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700347void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700348 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700349}
350
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700351static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700352 DCHECK(out_value != NULL);
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700353 jfieldID field = env->GetStaticFieldID(clz, name, "I");
354 if (field == NULL) {
355 env->ExceptionClear();
356 return false;
357 }
358 *out_value = env->GetStaticIntField(clz, field);
359 return true;
360}
361
362void Heap::ListenForProcessStateChange() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700363 VLOG(heap) << "Heap notified of process state change";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700364
365 Thread* self = Thread::Current();
366 JNIEnvExt* env = self->GetJniEnv();
367
368 if (!have_zygote_space_) {
369 return;
370 }
371
372 if (activity_thread_class_ == NULL) {
373 jclass clz = env->FindClass("android/app/ActivityThread");
374 if (clz == NULL) {
375 env->ExceptionClear();
376 LOG(WARNING) << "Could not find activity thread class in process state change";
377 return;
378 }
379 activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
380 }
381
382 if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
383 jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
384 "currentActivityThread",
385 "()Landroid/app/ActivityThread;");
386 if (current_activity_method == NULL) {
387 env->ExceptionClear();
388 LOG(WARNING) << "Could not get method for currentActivityThread";
389 return;
390 }
391
392 jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
393 if (obj == NULL) {
394 env->ExceptionClear();
395 LOG(WARNING) << "Could not get current activity";
396 return;
397 }
398 activity_thread_ = env->NewGlobalRef(obj);
399 }
400
401 if (process_state_cares_about_pause_time_.empty()) {
402 // Just attempt to do this the first time.
403 jclass clz = env->FindClass("android/app/ActivityManager");
404 if (clz == NULL) {
405 LOG(WARNING) << "Activity manager class is null";
406 return;
407 }
408 ScopedLocalRef<jclass> activity_manager(env, clz);
409 std::vector<const char*> care_about_pauses;
410 care_about_pauses.push_back("PROCESS_STATE_TOP");
411 care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
412 // Attempt to read the constants and classify them as whether or not we care about pause times.
413 for (size_t i = 0; i < care_about_pauses.size(); ++i) {
414 int process_state = 0;
415 if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
416 process_state_cares_about_pause_time_.insert(process_state);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700417 VLOG(heap) << "Adding process state " << process_state
418 << " to set of states which care about pause time";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700419 }
420 }
421 }
422
423 if (application_thread_class_ == NULL) {
424 jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
425 if (clz == NULL) {
426 env->ExceptionClear();
427 LOG(WARNING) << "Could not get application thread class";
428 return;
429 }
430 application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
431 last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
432 if (last_process_state_id_ == NULL) {
433 env->ExceptionClear();
434 LOG(WARNING) << "Could not get last process state member";
435 return;
436 }
437 }
438
439 if (application_thread_class_ != NULL && application_thread_ == NULL) {
440 jmethodID get_application_thread =
441 env->GetMethodID(activity_thread_class_, "getApplicationThread",
442 "()Landroid/app/ActivityThread$ApplicationThread;");
443 if (get_application_thread == NULL) {
444 LOG(WARNING) << "Could not get method ID for get application thread";
445 return;
446 }
447
448 jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
449 if (obj == NULL) {
450 LOG(WARNING) << "Could not get application thread";
451 return;
452 }
453
454 application_thread_ = env->NewGlobalRef(obj);
455 }
456
457 if (application_thread_ != NULL && last_process_state_id_ != NULL) {
458 int process_state = env->GetIntField(application_thread_, last_process_state_id_);
459 env->ExceptionClear();
460
461 care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
462 process_state_cares_about_pause_time_.end();
463
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700464 VLOG(heap) << "New process state " << process_state
465 << " care about pauses " << care_about_pause_times_;
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700466 }
Mathieu Chartier82353312013-07-18 10:47:51 -0700467}
468
Mathieu Chartier590fee92013-09-13 13:46:47 -0700469void Heap::AddSpace(space::Space* space) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700470 DCHECK(space != NULL);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700471 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
472 if (space->IsContinuousSpace()) {
473 DCHECK(!space->IsDiscontinuousSpace());
474 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
475 // Continuous spaces don't necessarily have bitmaps.
476 accounting::SpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
477 accounting::SpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
478 if (live_bitmap != nullptr) {
479 DCHECK(mark_bitmap != nullptr);
480 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
481 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700482 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700483
484 continuous_spaces_.push_back(continuous_space);
485 if (continuous_space->IsDlMallocSpace()) {
486 non_moving_space_ = continuous_space->AsDlMallocSpace();
487 }
488
489 // Ensure that spaces remain sorted in increasing order of start address.
490 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
491 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
492 return a->Begin() < b->Begin();
493 });
494 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
495 // avoid redundant marking.
496 bool seen_zygote = false, seen_alloc = false;
497 for (const auto& space : continuous_spaces_) {
498 if (space->IsImageSpace()) {
499 CHECK(!seen_zygote);
500 CHECK(!seen_alloc);
501 } else if (space->IsZygoteSpace()) {
502 CHECK(!seen_alloc);
503 seen_zygote = true;
504 } else if (space->IsDlMallocSpace()) {
505 seen_alloc = true;
506 }
507 }
508 } else {
509 DCHECK(space->IsDiscontinuousSpace());
510 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
511 DCHECK(discontinuous_space->GetLiveObjects() != nullptr);
512 live_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetLiveObjects());
513 DCHECK(discontinuous_space->GetMarkObjects() != nullptr);
514 mark_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetMarkObjects());
515 discontinuous_spaces_.push_back(discontinuous_space);
516 }
517 if (space->IsAllocSpace()) {
518 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700519 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800520}
521
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700522void Heap::RegisterGCAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700523 if (this != nullptr) {
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700524 gc_memory_overhead_.fetch_add(bytes);
525 }
526}
527
528void Heap::RegisterGCDeAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700529 if (this != nullptr) {
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700530 gc_memory_overhead_.fetch_sub(bytes);
531 }
532}
533
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700534void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700535 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700536 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700537 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800538
539 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800540 uint64_t total_paused_time = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700541 for (const auto& collector : garbage_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800542 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800543 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700544 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800545 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700546 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800547 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
548 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
549 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700550 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
551 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
552 << collector->GetName() << " freed: " << freed_objects
553 << " objects with total size " << PrettySize(freed_bytes) << "\n"
554 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
555 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800556 total_duration += total_ns;
557 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700558 }
559 }
560 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700561 size_t total_objects_allocated = GetObjectsAllocatedEver();
562 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700563 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700564 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700565 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
566 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700567 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700568 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700569 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700570 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700571 os << "Total number of allocations: " << total_objects_allocated << "\n";
572 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700573 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700574 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
575 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
576 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700577 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700578 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
579 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700580 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700581}
582
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800583Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700584 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700585 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700586 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700587 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700588 STLDeleteElements(&garbage_collectors_);
589 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700590 allocation_stack_->Reset();
591 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700592 STLDeleteValues(&mod_union_tables_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700593 STLDeleteElements(&continuous_spaces_);
594 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700595 delete gc_complete_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700596 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700597}
598
Ian Rogers1d54e732013-05-02 21:10:01 -0700599space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
600 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700601 for (const auto& space : continuous_spaces_) {
602 if (space->Contains(obj)) {
603 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700604 }
605 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700606 if (!fail_ok) {
607 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
608 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700609 return NULL;
610}
611
Ian Rogers1d54e732013-05-02 21:10:01 -0700612space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
613 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700614 for (const auto& space : discontinuous_spaces_) {
615 if (space->Contains(obj)) {
616 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700617 }
618 }
619 if (!fail_ok) {
620 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
621 }
622 return NULL;
623}
624
625space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
626 space::Space* result = FindContinuousSpaceFromObject(obj, true);
627 if (result != NULL) {
628 return result;
629 }
630 return FindDiscontinuousSpaceFromObject(obj, true);
631}
632
Mathieu Chartier39e32612013-11-12 16:28:05 -0800633struct SoftReferenceArgs {
634 RootVisitor* is_marked_callback_;
635 RootVisitor* recursive_mark_callback_;
636 void* arg_;
637};
638
639mirror::Object* Heap::PreserveSoftReferenceCallback(mirror::Object* obj, void* arg) {
640 SoftReferenceArgs* args = reinterpret_cast<SoftReferenceArgs*>(arg);
641 // TODO: Not preserve all soft references.
642 return args->recursive_mark_callback_(obj, args->arg_);
643}
644
645// Process reference class instances and schedule finalizations.
646void Heap::ProcessReferences(TimingLogger& timings, bool clear_soft,
647 RootVisitor* is_marked_callback,
648 RootVisitor* recursive_mark_object_callback, void* arg) {
649 // Unless we are in the zygote or required to clear soft references with white references,
650 // preserve some white referents.
651 if (!clear_soft && !Runtime::Current()->IsZygote()) {
652 SoftReferenceArgs soft_reference_args;
653 soft_reference_args.is_marked_callback_ = is_marked_callback;
654 soft_reference_args.recursive_mark_callback_ = recursive_mark_object_callback;
655 soft_reference_args.arg_ = arg;
656 soft_reference_queue_.PreserveSomeSoftReferences(&PreserveSoftReferenceCallback,
657 &soft_reference_args);
658 }
659 timings.StartSplit("ProcessReferences");
660 // Clear all remaining soft and weak references with white referents.
661 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
662 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
663 timings.EndSplit();
664 // Preserve all white objects with finalize methods and schedule them for finalization.
665 timings.StartSplit("EnqueueFinalizerReferences");
666 finalizer_reference_queue_.EnqueueFinalizerReferences(cleared_references_, is_marked_callback,
667 recursive_mark_object_callback, arg);
668 timings.EndSplit();
669 timings.StartSplit("ProcessReferences");
670 // Clear all f-reachable soft and weak references with white referents.
671 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
672 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
673 // Clear all phantom references with white referents.
674 phantom_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
675 // At this point all reference queues other than the cleared references should be empty.
676 DCHECK(soft_reference_queue_.IsEmpty());
677 DCHECK(weak_reference_queue_.IsEmpty());
678 DCHECK(finalizer_reference_queue_.IsEmpty());
679 DCHECK(phantom_reference_queue_.IsEmpty());
680 timings.EndSplit();
681}
682
683bool Heap::IsEnqueued(mirror::Object* ref) const {
684 // Since the references are stored as cyclic lists it means that once enqueued, the pending next
685 // will always be non-null.
686 return ref->GetFieldObject<mirror::Object*>(GetReferencePendingNextOffset(), false) != nullptr;
687}
688
689bool Heap::IsEnqueuable(const mirror::Object* ref) const {
690 DCHECK(ref != nullptr);
691 const mirror::Object* queue =
692 ref->GetFieldObject<mirror::Object*>(GetReferenceQueueOffset(), false);
693 const mirror::Object* queue_next =
694 ref->GetFieldObject<mirror::Object*>(GetReferenceQueueNextOffset(), false);
695 return queue != nullptr && queue_next == nullptr;
696}
697
698// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
699// marked, put it on the appropriate list in the heap for later processing.
700void Heap::DelayReferenceReferent(mirror::Class* klass, mirror::Object* obj,
701 RootVisitor mark_visitor, void* arg) {
702 DCHECK(klass != nullptr);
703 DCHECK(klass->IsReferenceClass());
704 DCHECK(obj != nullptr);
705 mirror::Object* referent = GetReferenceReferent(obj);
706 if (referent != nullptr) {
707 mirror::Object* forward_address = mark_visitor(referent, arg);
708 // Null means that the object is not currently marked.
709 if (forward_address == nullptr) {
710 Thread* self = Thread::Current();
711 // TODO: Remove these locks, and use atomic stacks for storing references?
712 // We need to check that the references haven't already been enqueued since we can end up
713 // scanning the same reference multiple times due to dirty cards.
714 if (klass->IsSoftReferenceClass()) {
715 soft_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
716 } else if (klass->IsWeakReferenceClass()) {
717 weak_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
718 } else if (klass->IsFinalizerReferenceClass()) {
719 finalizer_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
720 } else if (klass->IsPhantomReferenceClass()) {
721 phantom_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
722 } else {
723 LOG(FATAL) << "Invalid reference type " << PrettyClass(klass) << " " << std::hex
724 << klass->GetAccessFlags();
725 }
726 } else if (referent != forward_address) {
727 // Referent is already marked and we need to update it.
728 SetReferenceReferent(obj, forward_address);
729 }
730 }
731}
732
Ian Rogers1d54e732013-05-02 21:10:01 -0700733space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700734 for (const auto& space : continuous_spaces_) {
735 if (space->IsImageSpace()) {
736 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700737 }
738 }
739 return NULL;
740}
741
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700742static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700743 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700744 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700745 size_t chunk_free_bytes = chunk_size - used_bytes;
746 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
747 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700748 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700749}
750
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700751void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, bool large_object_allocation) {
752 std::ostringstream oss;
753 int64_t total_bytes_free = GetFreeMemory();
754 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
755 << " free bytes";
756 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
757 if (!large_object_allocation && total_bytes_free >= byte_count) {
758 size_t max_contiguous_allocation = 0;
759 for (const auto& space : continuous_spaces_) {
760 if (space->IsDlMallocSpace()) {
761 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
762 }
763 }
764 oss << "; failed due to fragmentation (largest possible contiguous allocation "
765 << max_contiguous_allocation << " bytes)";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700766 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700767 self->ThrowOutOfMemoryError(oss.str().c_str());
768}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700769
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700770inline bool Heap::TryAllocLargeObjectInstrumented(Thread* self, mirror::Class* c, size_t byte_count,
771 mirror::Object** obj_ptr, size_t* bytes_allocated) {
772 bool large_object_allocation = ShouldAllocLargeObject(c, byte_count);
Ian Rogers333cf1b2013-07-24 11:57:02 -0700773 if (UNLIKELY(large_object_allocation)) {
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700774 mirror::Object* obj = AllocateInstrumented(self, large_object_space_, byte_count, bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700775 // Make sure that our large object didn't get placed anywhere within the space interval or else
776 // it breaks the immune range.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700777 DCHECK(obj == nullptr ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700778 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
779 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700780 *obj_ptr = obj;
781 }
782 return large_object_allocation;
783}
784
Mathieu Chartier590fee92013-09-13 13:46:47 -0700785mirror::Object* Heap::AllocMovableObjectInstrumented(Thread* self, mirror::Class* c,
786 size_t byte_count) {
787 DebugCheckPreconditionsForAllocObject(c, byte_count);
788 mirror::Object* obj;
789 AllocationTimer alloc_timer(this, &obj);
790 byte_count = RoundUp(byte_count, 8);
791 if (UNLIKELY(IsOutOfMemoryOnAllocation(byte_count, false))) {
792 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, false);
793 if (UNLIKELY(IsOutOfMemoryOnAllocation(byte_count, true))) {
794 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
795 }
796 }
797 obj = bump_pointer_space_->AllocNonvirtual(byte_count);
798 if (LIKELY(obj != NULL)) {
799 obj->SetClass(c);
800 DCHECK(!obj->IsClass());
801 // Record allocation after since we want to use the atomic add for the atomic fence to guard
802 // the SetClass since we do not want the class to appear NULL in another thread.
803 num_bytes_allocated_.fetch_add(byte_count);
804 if (Runtime::Current()->HasStatsEnabled()) {
805 RuntimeStats* thread_stats = Thread::Current()->GetStats();
806 ++thread_stats->allocated_objects;
807 thread_stats->allocated_bytes += byte_count;
808 RuntimeStats* global_stats = Runtime::Current()->GetStats();
809 ++global_stats->allocated_objects;
810 global_stats->allocated_bytes += byte_count;
811 }
812 if (Dbg::IsAllocTrackingEnabled()) {
813 Dbg::RecordAllocation(c, byte_count);
814 }
815 if (kDesiredHeapVerification > kNoHeapVerification) {
816 VerifyObject(obj);
817 }
818 } else {
819 ThrowOutOfMemoryError(self, byte_count, false);
820 }
821 if (kIsDebugBuild) {
822 self->VerifyStack();
823 }
824 return obj;
825}
826
827mirror::Object* Heap::AllocNonMovableObjectInstrumented(Thread* self, mirror::Class* c,
828 size_t byte_count) {
829 DebugCheckPreconditionsForAllocObject(c, byte_count);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700830 mirror::Object* obj;
831 size_t bytes_allocated;
832 AllocationTimer alloc_timer(this, &obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700833 bool large_object_allocation = TryAllocLargeObjectInstrumented(self, c, byte_count, &obj,
834 &bytes_allocated);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700835 if (LIKELY(!large_object_allocation)) {
836 // Non-large object allocation.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700837 obj = AllocateInstrumented(self, non_moving_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700838 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700839 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700840 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700841 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700842 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700843 // Record allocation after since we want to use the atomic add for the atomic fence to guard
844 // the SetClass since we do not want the class to appear NULL in another thread.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700845 size_t new_num_bytes_allocated = RecordAllocationInstrumented(bytes_allocated, obj);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700846 if (Dbg::IsAllocTrackingEnabled()) {
847 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700848 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700849 CheckConcurrentGC(self, new_num_bytes_allocated, obj);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700850 if (kDesiredHeapVerification > kNoHeapVerification) {
851 VerifyObject(obj);
852 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700853 } else {
854 ThrowOutOfMemoryError(self, byte_count, large_object_allocation);
Carl Shapiro58551df2011-07-24 03:09:51 -0700855 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700856 if (kIsDebugBuild) {
857 self->VerifyStack();
858 }
859 return obj;
Carl Shapiro58551df2011-07-24 03:09:51 -0700860}
861
Mathieu Chartier590fee92013-09-13 13:46:47 -0700862void Heap::Trim() {
863 uint64_t start_ns = NanoTime();
864 // Trim the managed spaces.
865 uint64_t total_alloc_space_allocated = 0;
866 uint64_t total_alloc_space_size = 0;
867 uint64_t managed_reclaimed = 0;
868 for (const auto& space : continuous_spaces_) {
869 if (space->IsDlMallocSpace() && !space->IsZygoteSpace()) {
870 gc::space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
871 total_alloc_space_size += alloc_space->Size();
872 managed_reclaimed += alloc_space->Trim();
873 }
874 }
875 total_alloc_space_allocated = GetBytesAllocated() - large_object_space_->GetBytesAllocated() -
876 bump_pointer_space_->GetBytesAllocated();
877 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
878 static_cast<float>(total_alloc_space_size);
879 uint64_t gc_heap_end_ns = NanoTime();
880 // Trim the native heap.
881 dlmalloc_trim(0);
882 size_t native_reclaimed = 0;
883 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
884 uint64_t end_ns = NanoTime();
885 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
886 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
887 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
888 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
889 << "%.";
890}
891
892bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
893 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
894 // taking the lock.
895 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -0700896 return true;
897 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700898 return IsAligned<kObjectAlignment>(obj) && IsHeapAddress(obj);
899}
900
901bool Heap::IsHeapAddress(const mirror::Object* obj) const {
902 if (kMovingCollector && bump_pointer_space_->HasAddress(obj)) {
903 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700904 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700905 // TODO: This probably doesn't work for large objects.
906 return FindSpaceFromObject(obj, true) != nullptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700907}
908
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700909bool Heap::IsLiveObjectLocked(const mirror::Object* obj, bool search_allocation_stack,
910 bool search_live_stack, bool sorted) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700911 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700912 if (obj == nullptr || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700913 return false;
914 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700915 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
916 space::DiscontinuousSpace* d_space = NULL;
917 if (c_space != NULL) {
918 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700919 return true;
920 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700921 } else if (bump_pointer_space_->Contains(obj) || temp_space_->Contains(obj)) {
922 return true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700923 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700924 d_space = FindDiscontinuousSpaceFromObject(obj, true);
925 if (d_space != NULL) {
926 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700927 return true;
928 }
929 }
930 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700931 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700932 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
933 if (i > 0) {
934 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -0700935 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700936 if (search_allocation_stack) {
937 if (sorted) {
938 if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
939 return true;
940 }
941 } else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
942 return true;
943 }
944 }
945
946 if (search_live_stack) {
947 if (sorted) {
948 if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
949 return true;
950 }
951 } else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
952 return true;
953 }
954 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700955 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700956 // We need to check the bitmaps again since there is a race where we mark something as live and
957 // then clear the stack containing it.
958 if (c_space != NULL) {
959 if (c_space->GetLiveBitmap()->Test(obj)) {
960 return true;
961 }
962 } else {
963 d_space = FindDiscontinuousSpaceFromObject(obj, true);
964 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
965 return true;
966 }
967 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700968 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700969}
970
Ian Rogers04d7aa92013-03-16 14:29:17 -0700971void Heap::VerifyObjectImpl(const mirror::Object* obj) {
972 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700973 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700974 return;
975 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700976 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700977}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700978
Mathieu Chartier590fee92013-09-13 13:46:47 -0700979void Heap::DumpSpaces(std::ostream& stream) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700980 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700981 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
982 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700983 stream << space << " " << *space << "\n";
984 if (live_bitmap != nullptr) {
985 stream << live_bitmap << " " << *live_bitmap << "\n";
986 }
987 if (mark_bitmap != nullptr) {
988 stream << mark_bitmap << " " << *mark_bitmap << "\n";
989 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700990 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700991 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700992 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700993 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700994}
995
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800996void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700997 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
998 // Ignore early dawn of the universe verifications.
999 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.load()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001000 return;
1001 }
1002 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
1003 mirror::Object::ClassOffset().Int32Value();
1004 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
1005 if (UNLIKELY(c == NULL)) {
1006 LOG(FATAL) << "Null class in object: " << obj;
1007 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
1008 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
1009 }
1010 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
1011 // Note: we don't use the accessors here as they have internal sanity checks
1012 // that we don't want to run
1013 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
1014 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
1015 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
1016 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
1017 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001018
Mathieu Chartier590fee92013-09-13 13:46:47 -07001019 if (verify_object_mode_ > kVerifyAllFast) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001020 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
1021 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -07001022 if (!IsLiveObjectLocked(obj)) {
1023 DumpSpaces();
1024 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001025 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001026 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001027 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
1028 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001029 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001030}
1031
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001032void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001033 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001034 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001035}
1036
1037void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001038 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001039 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001040}
1041
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001042inline size_t Heap::RecordAllocationInstrumented(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001043 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001044 DCHECK_GT(size, 0u);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001045 size_t old_num_bytes_allocated = static_cast<size_t>(num_bytes_allocated_.fetch_add(size));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001046
1047 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001048 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001049 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001050 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001051
1052 // TODO: Update these atomically.
1053 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1054 ++global_stats->allocated_objects;
1055 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001056 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001057
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001058 // This is safe to do since the GC will never free objects which are neither in the allocation
1059 // stack or the live bitmap.
1060 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001061 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001062 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001063
1064 return old_num_bytes_allocated + size;
Carl Shapiro58551df2011-07-24 03:09:51 -07001065}
1066
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001067void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001068 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001069 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001070
1071 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001072 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001073 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001074 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001075
1076 // TODO: Do this concurrently.
1077 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1078 global_stats->freed_objects += freed_objects;
1079 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001080 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001081}
1082
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001083inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::AllocSpace* space, size_t alloc_size,
1084 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -07001085 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001086 return NULL;
1087 }
1088 return space->Alloc(self, alloc_size, bytes_allocated);
1089}
1090
1091// DlMallocSpace-specific version.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001092inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
1093 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -07001094 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001095 return nullptr;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001096 }
Mathieu Chartier720ef762013-08-17 14:46:54 -07001097 if (LIKELY(!running_on_valgrind_)) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001098 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
1099 } else {
1100 return space->Alloc(self, alloc_size, bytes_allocated);
1101 }
1102}
1103
1104template <class T>
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001105inline mirror::Object* Heap::AllocateInstrumented(Thread* self, T* space, size_t alloc_size,
1106 size_t* bytes_allocated) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001107 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
1108 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -07001109 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001110 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -07001111
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001112 mirror::Object* ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
1113 if (LIKELY(ptr != NULL)) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001114 return ptr;
1115 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001116 return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
1117}
1118
Mathieu Chartier720ef762013-08-17 14:46:54 -07001119mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space,
1120 size_t alloc_size, size_t* bytes_allocated) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001121 mirror::Object* ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001122
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001123 // The allocation failed. If the GC is running, block until it completes, and then retry the
1124 // allocation.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001125 collector::GcType last_gc = WaitForGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001126 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001127 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001128 ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001129 if (ptr != NULL) {
1130 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001131 }
1132 }
1133
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001134 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -07001135 for (size_t i = static_cast<size_t>(last_gc) + 1;
1136 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001137 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -07001138 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001139 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001140 case collector::kGcTypeSticky: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001141 const size_t alloc_space_size = non_moving_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001142 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
Mathieu Chartier590fee92013-09-13 13:46:47 -07001143 non_moving_space_->Capacity() - alloc_space_size >=
1144 min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001145 break;
1146 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001147 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001148 run_gc = have_zygote_space_;
1149 break;
Ian Rogers1d54e732013-05-02 21:10:01 -07001150 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001151 run_gc = true;
1152 break;
1153 default:
Mathieu Chartier590fee92013-09-13 13:46:47 -07001154 LOG(FATAL) << "Invalid GC type";
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001155 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001156
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001157 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001158 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -07001159 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001160 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001161 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001162
1163 // Did we free sufficient memory for the allocation to succeed?
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001164 ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001165 if (ptr != NULL) {
1166 return ptr;
1167 }
1168 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001169 }
1170
1171 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001172 // Try harder, growing the heap if necessary.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001173 ptr = TryToAllocateInstrumented(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001174 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001175 return ptr;
1176 }
1177
Elliott Hughes81ff3182012-03-23 20:35:56 -07001178 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1179 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1180 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001181
Mathieu Chartier590fee92013-09-13 13:46:47 -07001182 // TODO: Run finalization, but this can cause more allocations to occur.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001183 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1184 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001185
Mathieu Chartier590fee92013-09-13 13:46:47 -07001186 // We don't need a WaitForGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -07001187 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001188 return TryToAllocateInstrumented(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001189}
1190
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001191void Heap::SetTargetHeapUtilization(float target) {
1192 DCHECK_GT(target, 0.0f); // asserted in Java code
1193 DCHECK_LT(target, 1.0f);
1194 target_utilization_ = target;
1195}
1196
Ian Rogers1d54e732013-05-02 21:10:01 -07001197size_t Heap::GetObjectsAllocated() const {
1198 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001199 for (space::AllocSpace* space : alloc_spaces_) {
1200 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001201 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001202 return total;
1203}
1204
Ian Rogers1d54e732013-05-02 21:10:01 -07001205size_t Heap::GetObjectsAllocatedEver() const {
1206 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001207 for (space::AllocSpace* space : alloc_spaces_) {
1208 total += space->GetTotalObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001209 }
1210 return total;
1211}
1212
1213size_t Heap::GetBytesAllocatedEver() const {
1214 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001215 for (space::AllocSpace* space : alloc_spaces_) {
1216 total += space->GetTotalBytesAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001217 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001218 return total;
1219}
1220
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001221class InstanceCounter {
1222 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001223 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001224 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001225 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001226 }
1227
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001228 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001229 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001230 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001231 if (use_is_assignable_from_) {
1232 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
1233 ++counts_[i];
1234 }
1235 } else {
1236 if (instance_class == classes_[i]) {
1237 ++counts_[i];
1238 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001239 }
1240 }
1241 }
1242
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001243 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001244 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001245 bool use_is_assignable_from_;
1246 uint64_t* const counts_;
1247
1248 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001249};
1250
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001251void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001252 uint64_t* counts) {
1253 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1254 // is empty, so the live bitmap is the only place we need to look.
1255 Thread* self = Thread::Current();
1256 self->TransitionFromRunnableToSuspended(kNative);
1257 CollectGarbage(false);
1258 self->TransitionFromSuspendedToRunnable();
1259
1260 InstanceCounter counter(classes, use_is_assignable_from, counts);
1261 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001262 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001263}
1264
Elliott Hughes3b78c942013-01-15 17:35:41 -08001265class InstanceCollector {
1266 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001267 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001268 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1269 : class_(c), max_count_(max_count), instances_(instances) {
1270 }
1271
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001272 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1273 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001274 if (instance_class == class_) {
1275 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001276 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001277 }
1278 }
1279 }
1280
1281 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001282 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001283 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001284 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001285
1286 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1287};
1288
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001289void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1290 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001291 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1292 // is empty, so the live bitmap is the only place we need to look.
1293 Thread* self = Thread::Current();
1294 self->TransitionFromRunnableToSuspended(kNative);
1295 CollectGarbage(false);
1296 self->TransitionFromSuspendedToRunnable();
1297
1298 InstanceCollector collector(c, max_count, instances);
1299 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1300 GetLiveBitmap()->Visit(collector);
1301}
1302
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001303class ReferringObjectsFinder {
1304 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001305 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1306 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001307 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1308 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1309 }
1310
1311 // For bitmap Visit.
1312 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1313 // annotalysis on visitors.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001314 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
1315 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(o), *this, true);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001316 }
1317
1318 // For MarkSweep::VisitObjectReferences.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001319 void operator()(mirror::Object* referrer, mirror::Object* object,
Brian Carlstromdf629502013-07-17 22:39:56 -07001320 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001321 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001322 referring_objects_.push_back(referrer);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001323 }
1324 }
1325
1326 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001327 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001328 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001329 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001330
1331 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1332};
1333
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001334void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1335 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001336 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1337 // is empty, so the live bitmap is the only place we need to look.
1338 Thread* self = Thread::Current();
1339 self->TransitionFromRunnableToSuspended(kNative);
1340 CollectGarbage(false);
1341 self->TransitionFromSuspendedToRunnable();
1342
1343 ReferringObjectsFinder finder(o, max_count, referring_objects);
1344 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1345 GetLiveBitmap()->Visit(finder);
1346}
1347
Ian Rogers30fab402012-01-23 15:43:46 -08001348void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001349 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1350 // last GC will not have necessarily been cleared.
Ian Rogers1d54e732013-05-02 21:10:01 -07001351 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001352}
1353
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001354void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001355 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -07001356 Thread* self = Thread::Current();
1357 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001358 // Try to see if we have any Zygote spaces.
1359 if (have_zygote_space_) {
1360 return;
1361 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001362 VLOG(heap) << "Starting PreZygoteFork";
1363 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1364 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
1365 // Trim the pages at the end of the non moving space.
1366 non_moving_space_->Trim();
1367 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1368 // Create a new bump pointer space which we will compact into.
1369 if (semi_space_collector_ != nullptr) {
1370 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1371 non_moving_space_->Limit());
1372 // Compact the bump pointer space to a new zygote bump pointer space.
1373 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1374 Compact(&target_space, bump_pointer_space_);
1375 CHECK_EQ(temp_space_->GetBytesAllocated(), 0U);
1376 total_objects_freed_ever_ += semi_space_collector_->GetFreedObjects();
1377 total_bytes_freed_ever_ += semi_space_collector_->GetFreedBytes();
1378 // Update the end and write out image.
1379 non_moving_space_->SetEnd(target_space.End());
1380 non_moving_space_->SetLimit(target_space.Limit());
1381 accounting::SpaceBitmap* bitmap = non_moving_space_->GetLiveBitmap();
1382 // Record the allocations in the bitmap.
1383 VLOG(heap) << "Recording zygote allocations";
1384 mirror::Object* obj = reinterpret_cast<mirror::Object*>(target_space.Begin());
1385 const mirror::Object* end = reinterpret_cast<const mirror::Object*>(target_space.End());
1386 while (obj < end) {
1387 bitmap->Set(obj);
1388 obj = space::BumpPointerSpace::GetNextObject(obj);
1389 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001390 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001391 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
1392 // the remaining available heap memory.
1393 space::DlMallocSpace* zygote_space = non_moving_space_;
1394 non_moving_space_ = zygote_space->CreateZygoteSpace("alloc space");
1395 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -07001396 // Change the GC retention policy of the zygote space to only collect when full.
1397 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001398 AddSpace(non_moving_space_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001399 have_zygote_space_ = true;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001400 zygote_space->InvalidateMSpace();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001401 // Create the zygote space mod union table.
1402 accounting::ModUnionTable* mod_union_table =
1403 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1404 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1405 AddModUnionTable(mod_union_table);
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001406 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001407 for (const auto& collector : garbage_collectors_) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001408 collector->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001409 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001410}
1411
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001412void Heap::FlushAllocStack() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001413 MarkAllocStack(non_moving_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001414 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001415 allocation_stack_->Reset();
1416}
1417
Ian Rogers1d54e732013-05-02 21:10:01 -07001418void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1419 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001420 mirror::Object** limit = stack->End();
1421 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1422 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001423 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001424 if (LIKELY(bitmap->HasAddress(obj))) {
1425 bitmap->Set(obj);
1426 } else {
1427 large_objects->Set(obj);
1428 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001429 }
1430}
1431
Mathieu Chartier590fee92013-09-13 13:46:47 -07001432const char* PrettyCause(GcCause cause) {
1433 switch (cause) {
1434 case kGcCauseForAlloc: return "Alloc";
1435 case kGcCauseBackground: return "Background";
1436 case kGcCauseExplicit: return "Explicit";
1437 default:
1438 LOG(FATAL) << "Unreachable";
1439 }
1440 return "";
1441}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001442
Mathieu Chartier590fee92013-09-13 13:46:47 -07001443void Heap::SwapSemiSpaces() {
1444 // Swap the spaces so we allocate into the space which we just evacuated.
1445 std::swap(bump_pointer_space_, temp_space_);
1446}
1447
1448void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
1449 space::ContinuousMemMapAllocSpace* source_space) {
1450 CHECK(kMovingCollector);
1451 CHECK_NE(target_space, source_space) << "In-place compaction unsupported";
1452 if (target_space != source_space) {
1453 semi_space_collector_->SetFromSpace(source_space);
1454 semi_space_collector_->SetToSpace(target_space);
1455 semi_space_collector_->Run(false);
1456 }
1457}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001458
Ian Rogers1d54e732013-05-02 21:10:01 -07001459collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1460 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001461 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001462 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001463 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001464 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001465 if (self->IsHandlingStackOverflow()) {
1466 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1467 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001468 {
1469 gc_complete_lock_->AssertNotHeld(self);
1470 MutexLock mu(self, *gc_complete_lock_);
1471 // Ensure there is only one GC at a time.
1472 WaitForGcToCompleteLocked(self);
1473 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1474 // Not doing at the moment to ensure soft references are cleared.
1475 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
1476 if (gc_disable_count_ != 0) {
1477 LOG(WARNING) << "Skipping GC due to disable count " << gc_disable_count_;
1478 return collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001479 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001480 is_gc_running_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001481 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001482
Mathieu Chartier590fee92013-09-13 13:46:47 -07001483 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
1484 ++runtime->GetStats()->gc_for_alloc_count;
1485 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001486 }
1487
Ian Rogers1d54e732013-05-02 21:10:01 -07001488 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001489 uint64_t gc_start_size = GetBytesAllocated();
1490 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001491 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001492 // Back to back GCs can cause 0 ms of wait time in between GC invocations.
1493 if (LIKELY(ms_delta != 0)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001494 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001495 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1496 }
1497
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001498 if (gc_type == collector::kGcTypeSticky &&
Mathieu Chartier590fee92013-09-13 13:46:47 -07001499 non_moving_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001500 gc_type = collector::kGcTypePartial;
1501 }
1502
Ian Rogers1d54e732013-05-02 21:10:01 -07001503 DCHECK_LT(gc_type, collector::kGcTypeMax);
1504 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001505
Mathieu Chartier590fee92013-09-13 13:46:47 -07001506 collector::GarbageCollector* collector = nullptr;
1507 if (kMovingCollector) {
1508 gc_type = semi_space_collector_->GetGcType();
1509 CHECK_EQ(temp_space_->GetObjectsAllocated(), 0U);
1510 semi_space_collector_->SetFromSpace(bump_pointer_space_);
1511 semi_space_collector_->SetToSpace(temp_space_);
1512 mprotect(temp_space_->Begin(), temp_space_->Capacity(), PROT_READ | PROT_WRITE);
1513 }
1514 for (const auto& cur_collector : garbage_collectors_) {
1515 if (cur_collector->IsConcurrent() == concurrent_gc_ &&
1516 cur_collector->GetGcType() == gc_type) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001517 collector = cur_collector;
1518 break;
1519 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001520 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001521 if (kMovingCollector) {
1522 gc_type = collector::kGcTypeFull;
1523 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001524 CHECK(collector != NULL)
1525 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1526 << " and type=" << gc_type;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001527
Mathieu Chartier590fee92013-09-13 13:46:47 -07001528 ATRACE_BEGIN(StringPrintf("%s %s GC", PrettyCause(gc_cause), collector->GetName()).c_str());
1529
1530 collector->Run(clear_soft_references);
Ian Rogers1d54e732013-05-02 21:10:01 -07001531 total_objects_freed_ever_ += collector->GetFreedObjects();
1532 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001533
Mathieu Chartier39e32612013-11-12 16:28:05 -08001534 // Enqueue cleared references.
1535 EnqueueClearedReferences();
1536
Mathieu Chartier590fee92013-09-13 13:46:47 -07001537 // Grow the heap so that we know when to perform the next GC.
1538 GrowForUtilization(gc_type, collector->GetDurationNs());
1539
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001540 if (care_about_pause_times_) {
1541 const size_t duration = collector->GetDurationNs();
1542 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1543 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001544 bool was_slow = duration > long_gc_log_threshold_ ||
1545 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001546 if (!was_slow) {
1547 for (uint64_t pause : pauses) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001548 was_slow = was_slow || pause > long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001549 }
1550 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001551 if (was_slow) {
1552 const size_t percent_free = GetPercentFree();
1553 const size_t current_heap_size = GetBytesAllocated();
1554 const size_t total_memory = GetTotalMemory();
1555 std::ostringstream pause_string;
1556 for (size_t i = 0; i < pauses.size(); ++i) {
1557 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1558 << ((i != pauses.size() - 1) ? ", " : "");
1559 }
1560 LOG(INFO) << gc_cause << " " << collector->GetName()
1561 << " GC freed " << collector->GetFreedObjects() << "("
1562 << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1563 << collector->GetFreedLargeObjects() << "("
1564 << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1565 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1566 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1567 << " total " << PrettyDuration((duration / 1000) * 1000);
1568 if (VLOG_IS_ON(heap)) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001569 LOG(INFO) << Dumpable<TimingLogger>(collector->GetTimings());
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001570 }
1571 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001572 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001573
Ian Rogers15bf2d32012-08-28 17:33:04 -07001574 {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001575 MutexLock mu(self, *gc_complete_lock_);
1576 is_gc_running_ = false;
1577 last_gc_type_ = gc_type;
1578 // Wake anyone who may have been waiting for the GC to complete.
1579 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001580 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001581
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001582 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001583
1584 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001585 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001586 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001587}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001588
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001589static mirror::Object* RootMatchesObjectVisitor(mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001590 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001591 if (root == obj) {
1592 LOG(INFO) << "Object " << obj << " is a root";
1593 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001594 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001595}
1596
1597class ScanVisitor {
1598 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001599 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001600 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001601 }
1602};
1603
Ian Rogers1d54e732013-05-02 21:10:01 -07001604// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001605class VerifyReferenceVisitor {
1606 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001607 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001608 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001609 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001610
1611 bool Failed() const {
1612 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001613 }
1614
1615 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001616 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001617 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1618 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001619 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001620 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001621 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1622 accounting::CardTable* card_table = heap_->GetCardTable();
1623 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1624 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001625 if (!failed_) {
1626 // Print message on only on first failure to prevent spam.
1627 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
1628 failed_ = true;
1629 }
1630 if (obj != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001631 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001632 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
1633 << offset << "\n card value = " << static_cast<int>(*card_addr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001634 if (heap_->IsValidObjectAddress(obj->GetClass())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001635 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1636 } else {
1637 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
1638 }
1639
1640 // Attmept to find the class inside of the recently freed objects.
1641 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001642 if (ref_space != nullptr && ref_space->IsDlMallocSpace()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001643 space::DlMallocSpace* space = ref_space->AsDlMallocSpace();
1644 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
1645 if (ref_class != nullptr) {
1646 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
1647 << PrettyClass(ref_class);
1648 } else {
1649 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
1650 }
1651 }
1652
Mathieu Chartier590fee92013-09-13 13:46:47 -07001653 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001654 ref->GetClass()->IsClass()) {
1655 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1656 } else {
1657 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
1658 << ") is not a valid heap address";
1659 }
1660
Ian Rogers1d54e732013-05-02 21:10:01 -07001661 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1662 void* cover_begin = card_table->AddrFromCard(card_addr);
1663 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1664 accounting::CardTable::kCardSize);
1665 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1666 << "-" << cover_end;
1667 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001668
Ian Rogers1d54e732013-05-02 21:10:01 -07001669 // Print out how the object is live.
1670 if (bitmap != NULL && bitmap->Test(obj)) {
1671 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1672 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001673 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001674 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1675 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001676 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001677 LOG(ERROR) << "Object " << obj << " found in live stack";
1678 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001679 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1680 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
1681 }
1682 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1683 LOG(ERROR) << "Ref " << ref << " found in live stack";
1684 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001685 // Attempt to see if the card table missed the reference.
1686 ScanVisitor scan_visitor;
1687 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1688 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001689 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001690
1691 // Search to see if any of the roots reference our object.
1692 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1693 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1694
1695 // Search to see if any of the roots reference our reference.
1696 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1697 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1698 } else {
1699 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001700 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001701 }
1702 }
1703
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001704 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001705 return heap_->IsLiveObjectLocked(obj, true, false, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001706 }
1707
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001708 static mirror::Object* VerifyRoots(mirror::Object* root, void* arg) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001709 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001710 (*visitor)(nullptr, root, MemberOffset(0), true);
1711 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001712 }
1713
1714 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001715 Heap* const heap_;
1716 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001717};
1718
Ian Rogers1d54e732013-05-02 21:10:01 -07001719// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001720class VerifyObjectVisitor {
1721 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001722 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001723
Mathieu Chartier590fee92013-09-13 13:46:47 -07001724 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001725 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001726 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1727 // be live or else how did we find it in the live bitmap?
1728 VerifyReferenceVisitor visitor(heap_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001729 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001730 collector::MarkSweep::VisitObjectReferences(obj, visitor, true);
1731 if (obj->GetClass()->IsReferenceClass()) {
1732 visitor(obj, heap_->GetReferenceReferent(obj), MemberOffset(0), false);
1733 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001734 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001735 }
1736
Mathieu Chartier590fee92013-09-13 13:46:47 -07001737 static void VisitCallback(mirror::Object* obj, void* arg)
1738 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1739 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
1740 visitor->operator()(obj);
1741 }
1742
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001743 bool Failed() const {
1744 return failed_;
1745 }
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
1752// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001753bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001754 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001755 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001756 allocation_stack_->Sort();
1757 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001758 VerifyObjectVisitor visitor(this);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001759 // Verify objects in the allocation stack since these will be objects which were:
1760 // 1. Allocated prior to the GC (pre GC verification).
1761 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001762 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001763 // pointing to dead objects if they are not reachable.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001764 VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
1765 // Verify the roots:
1766 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001767 if (visitor.Failed()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001768 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001769 for (const auto& table_pair : mod_union_tables_) {
1770 accounting::ModUnionTable* mod_union_table = table_pair.second;
1771 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
1772 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001773 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001774 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001775 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001776 return true;
1777}
1778
1779class VerifyReferenceCardVisitor {
1780 public:
1781 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1782 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1783 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001784 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001785 }
1786
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001787 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1788 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001789 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1790 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001791 // Filter out class references since changing an object's class does not mark the card as dirty.
1792 // Also handles large objects, since the only reference they hold is a class reference.
1793 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001794 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001795 // If the object is not dirty and it is referencing something in the live stack other than
1796 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001797 if (!card_table->AddrIsInCardTable(obj)) {
1798 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1799 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001800 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001801 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1802 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001803 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001804 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1805 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001806 LOG(ERROR) << "Object " << obj << " found in live stack";
1807 }
1808 if (heap_->GetLiveBitmap()->Test(obj)) {
1809 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1810 }
1811 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1812 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1813
1814 // Print which field of the object is dead.
1815 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001816 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001817 CHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001818 const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
1819 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001820 CHECK(fields != NULL);
1821 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001822 const mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001823 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1824 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1825 << PrettyField(cur);
1826 break;
1827 }
1828 }
1829 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001830 const mirror::ObjectArray<mirror::Object>* object_array =
1831 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001832 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1833 if (object_array->Get(i) == ref) {
1834 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1835 }
1836 }
1837 }
1838
1839 *failed_ = true;
1840 }
1841 }
1842 }
1843 }
1844
1845 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001846 Heap* const heap_;
1847 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001848};
1849
1850class VerifyLiveStackReferences {
1851 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001852 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001853 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001854 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001855
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001856 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001857 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1858 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001859 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(obj), visitor, true);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001860 }
1861
1862 bool Failed() const {
1863 return failed_;
1864 }
1865
1866 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001867 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001868 bool failed_;
1869};
1870
1871bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001872 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001873
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001874 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001875 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001876 VerifyLiveStackReferences visitor(this);
1877 GetLiveBitmap()->Visit(visitor);
1878
1879 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001880 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001881 visitor(*it);
1882 }
1883
1884 if (visitor.Failed()) {
1885 DumpSpaces();
1886 return false;
1887 }
1888 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001889}
1890
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001891void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001892 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001893}
1894
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001895accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
1896 auto it = mod_union_tables_.find(space);
1897 if (it == mod_union_tables_.end()) {
1898 return nullptr;
1899 }
1900 return it->second;
1901}
1902
Ian Rogers5fe9af72013-11-14 00:17:20 -08001903void Heap::ProcessCards(TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001904 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001905 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001906 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
1907 if (table != nullptr) {
1908 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
1909 "ImageModUnionClearCards";
Ian Rogers5fe9af72013-11-14 00:17:20 -08001910 TimingLogger::ScopedSplit split(name, &timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001911 table->ClearCards();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001912 } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001913 TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001914 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1915 // were dirty before the GC started.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001916 // TODO: Don't need to use atomic.
1917 // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
1918 // roots and then we scan / update mod union tables after. We will always scan either card.//
1919 // If we end up with the non aged card, we scan it it in the pause.
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001920 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001921 }
1922 }
1923}
1924
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001925static mirror::Object* IdentityCallback(mirror::Object* obj, void*) {
1926 return obj;
1927}
1928
Ian Rogers1d54e732013-05-02 21:10:01 -07001929void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001930 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1931 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001932
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001933 if (verify_pre_gc_heap_) {
1934 thread_list->SuspendAll();
1935 {
1936 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1937 if (!VerifyHeapReferences()) {
1938 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1939 }
1940 }
1941 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001942 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001943
1944 // Check that all objects which reference things in the live stack are on dirty cards.
1945 if (verify_missing_card_marks_) {
1946 thread_list->SuspendAll();
1947 {
1948 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1949 SwapStacks();
1950 // Sort the live stack so that we can quickly binary search it later.
1951 if (!VerifyMissingCardMarks()) {
1952 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1953 }
1954 SwapStacks();
1955 }
1956 thread_list->ResumeAll();
1957 }
1958
1959 if (verify_mod_union_table_) {
1960 thread_list->SuspendAll();
1961 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001962 for (const auto& table_pair : mod_union_tables_) {
1963 accounting::ModUnionTable* mod_union_table = table_pair.second;
1964 mod_union_table->UpdateAndMarkReferences(IdentityCallback, nullptr);
1965 mod_union_table->Verify();
1966 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001967 thread_list->ResumeAll();
1968 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001969}
1970
Ian Rogers1d54e732013-05-02 21:10:01 -07001971void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001972 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1973 // reachable objects.
1974 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001975 Thread* self = Thread::Current();
1976 CHECK_NE(self->GetState(), kRunnable);
Ian Rogers1d54e732013-05-02 21:10:01 -07001977 {
1978 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1979 // Swapping bound bitmaps does nothing.
1980 gc->SwapBitmaps();
1981 if (!VerifyHeapReferences()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001982 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
Ian Rogers1d54e732013-05-02 21:10:01 -07001983 }
1984 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001985 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001986 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001987}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001988
Ian Rogers1d54e732013-05-02 21:10:01 -07001989void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001990 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001991 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001992 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001993 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001994 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001995 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001996}
1997
Mathieu Chartier590fee92013-09-13 13:46:47 -07001998collector::GcType Heap::WaitForGcToComplete(Thread* self) {
1999 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
2000 MutexLock mu(self, *gc_complete_lock_);
2001 return WaitForGcToCompleteLocked(self);
2002}
2003
2004collector::GcType Heap::WaitForGcToCompleteLocked(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002005 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002006 uint64_t wait_start = NanoTime();
2007 while (is_gc_running_) {
2008 ATRACE_BEGIN("GC: Wait For Completion");
2009 // We must wait, change thread state then sleep on gc_complete_cond_;
2010 gc_complete_cond_->Wait(self);
2011 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07002012 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002013 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002014 uint64_t wait_time = NanoTime() - wait_start;
2015 total_wait_time_ += wait_time;
2016 if (wait_time > long_pause_log_threshold_) {
2017 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time);
2018 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07002019 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07002020}
2021
Elliott Hughesc967f782012-04-16 10:23:15 -07002022void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002023 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002024 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07002025 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07002026}
2027
2028size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002029 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07002030}
2031
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002032void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002033 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002034 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002035 << PrettySize(GetMaxMemory());
2036 max_allowed_footprint = GetMaxMemory();
2037 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07002038 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07002039}
2040
Mathieu Chartier590fee92013-09-13 13:46:47 -07002041bool Heap::IsMovableObject(const mirror::Object* obj) const {
2042 if (kMovingCollector) {
2043 DCHECK(!IsInTempSpace(obj));
2044 if (bump_pointer_space_->HasAddress(obj)) {
2045 return true;
2046 }
2047 }
2048 return false;
2049}
2050
2051bool Heap::IsInTempSpace(const mirror::Object* obj) const {
2052 if (temp_space_->HasAddress(obj) && !temp_space_->Contains(obj)) {
2053 return true;
2054 }
2055 return false;
2056}
2057
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002058void Heap::UpdateMaxNativeFootprint() {
2059 size_t native_size = native_bytes_allocated_;
2060 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
2061 size_t target_size = native_size / GetTargetHeapUtilization();
2062 if (target_size > native_size + max_free_) {
2063 target_size = native_size + max_free_;
2064 } else if (target_size < native_size + min_free_) {
2065 target_size = native_size + min_free_;
2066 }
2067 native_footprint_gc_watermark_ = target_size;
2068 native_footprint_limit_ = 2 * target_size - native_size;
2069}
2070
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002071void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002072 // We know what our utilization is at this moment.
2073 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08002074 const size_t bytes_allocated = GetBytesAllocated();
2075 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07002076 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002077
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002078 size_t target_size;
2079 if (gc_type != collector::kGcTypeSticky) {
2080 // Grow the heap for non sticky GC.
2081 target_size = bytes_allocated / GetTargetHeapUtilization();
2082 if (target_size > bytes_allocated + max_free_) {
2083 target_size = bytes_allocated + max_free_;
2084 } else if (target_size < bytes_allocated + min_free_) {
2085 target_size = bytes_allocated + min_free_;
2086 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002087 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002088 next_gc_type_ = collector::kGcTypeSticky;
2089 } else {
2090 // Based on how close the current heap size is to the target size, decide
2091 // whether or not to do a partial or sticky GC next.
2092 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
2093 next_gc_type_ = collector::kGcTypeSticky;
2094 } else {
2095 next_gc_type_ = collector::kGcTypePartial;
2096 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002097
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002098 // If we have freed enough memory, shrink the heap back down.
2099 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
2100 target_size = bytes_allocated + max_free_;
2101 } else {
2102 target_size = std::max(bytes_allocated, max_allowed_footprint_);
2103 }
2104 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002105
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002106 if (!ignore_max_footprint_) {
2107 SetIdealFootprint(target_size);
2108
2109 if (concurrent_gc_) {
2110 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002111 // Calculate the estimated GC duration.
2112 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
2113 // Estimate how many remaining bytes we will have when we need to start the next GC.
2114 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
2115 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
2116 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
2117 // A never going to happen situation that from the estimated allocation rate we will exceed
2118 // the applications entire footprint with the given estimated allocation rate. Schedule
2119 // another GC straight away.
2120 concurrent_start_bytes_ = bytes_allocated;
2121 } else {
2122 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
2123 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
2124 // right away.
2125 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
2126 }
2127 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
2128 DCHECK_LE(max_allowed_footprint_, growth_limit_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08002129 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002130 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07002131}
2132
jeffhaoc1160702011-10-27 15:48:45 -07002133void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08002134 growth_limit_ = capacity_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002135 non_moving_space_->ClearGrowthLimit();
jeffhaoc1160702011-10-27 15:48:45 -07002136}
2137
Elliott Hughesadb460d2011-10-05 17:02:34 -07002138void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002139 MemberOffset reference_queue_offset,
2140 MemberOffset reference_queueNext_offset,
2141 MemberOffset reference_pendingNext_offset,
2142 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002143 reference_referent_offset_ = reference_referent_offset;
2144 reference_queue_offset_ = reference_queue_offset;
2145 reference_queueNext_offset_ = reference_queueNext_offset;
2146 reference_pendingNext_offset_ = reference_pendingNext_offset;
2147 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
2148 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
2149 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
2150 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
2151 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
2152 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
2153}
2154
Mathieu Chartier590fee92013-09-13 13:46:47 -07002155void Heap::SetReferenceReferent(mirror::Object* reference, mirror::Object* referent) {
2156 DCHECK(reference != NULL);
2157 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
2158 reference->SetFieldObject(reference_referent_offset_, referent, true);
2159}
2160
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002161mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002162 DCHECK(reference != NULL);
2163 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002164 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002165}
2166
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002167void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002168 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08002169 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08002170 ArgArray arg_array(NULL, 0);
2171 arg_array.Append(reinterpret_cast<uint32_t>(object));
2172 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07002173 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002174}
2175
Mathieu Chartier590fee92013-09-13 13:46:47 -07002176void Heap::PrintReferenceQueue(std::ostream& os, mirror::Object** queue) {
2177 os << "Refernece queue " << queue << "\n";
2178 if (queue != nullptr) {
2179 mirror::Object* list = *queue;
2180 if (list != nullptr) {
2181 mirror::Object* cur = list;
2182 do {
2183 mirror::Object* pending_next =
2184 cur->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
2185 os << "PendingNext=" << pending_next;
2186 if (cur->GetClass()->IsFinalizerReferenceClass()) {
2187 os << " Zombie=" <<
2188 cur->GetFieldObject<mirror::Object*>(finalizer_reference_zombie_offset_, false);
2189 }
2190 os << "\n";
2191 cur = pending_next;
2192 } while (cur != list);
2193 }
2194 }
2195}
2196
Mathieu Chartier39e32612013-11-12 16:28:05 -08002197void Heap::EnqueueClearedReferences() {
2198 if (!cleared_references_.IsEmpty()) {
Ian Rogers64b6d142012-10-29 16:34:15 -07002199 // When a runtime isn't started there are no reference queues to care about so ignore.
2200 if (LIKELY(Runtime::Current()->IsStarted())) {
2201 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08002202 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08002203 ArgArray arg_array(NULL, 0);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002204 arg_array.Append(reinterpret_cast<uint32_t>(cleared_references_.GetList()));
Jeff Hao5d917302013-02-27 17:57:33 -08002205 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07002206 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07002207 }
Mathieu Chartier39e32612013-11-12 16:28:05 -08002208 cleared_references_.Clear();
Elliott Hughesadb460d2011-10-05 17:02:34 -07002209 }
2210}
2211
Ian Rogers1f539342012-10-03 21:09:42 -07002212void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07002213 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07002214 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08002215 DCHECK(concurrent_gc_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002216 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
2217 self->IsHandlingStackOverflow()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002218 return;
2219 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002220 // We already have a request pending, no reason to start more until we update
2221 // concurrent_start_bytes_.
2222 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers120f1c72012-09-28 17:17:10 -07002223 JNIEnv* env = self->GetJniEnv();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002224 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2225 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002226 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2227 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002228 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002229}
2230
Ian Rogers81d425b2012-09-27 16:03:43 -07002231void Heap::ConcurrentGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002232 if (Runtime::Current()->IsShuttingDown(self)) {
2233 return;
Mathieu Chartier2542d662012-06-21 17:14:11 -07002234 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002235 // Wait for any GCs currently running to finish.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002236 if (WaitForGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002237 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002238 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002239}
2240
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002241void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08002242 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
2243 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
2244 // a space it will hold its lock and can become a cause of jank.
2245 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
2246 // forking.
2247
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002248 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2249 // because that only marks object heads, so a large array looks like lots of empty space. We
2250 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2251 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2252 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2253 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08002254 uint64_t ms_time = MilliTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002255 // Don't bother trimming the alloc space if a heap trim occurred in the last two seconds.
2256 if (ms_time - last_trim_time_ms_ < 2 * 1000) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002257 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002258 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002259
2260 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002261 Runtime* runtime = Runtime::Current();
2262 if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self)) {
2263 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2264 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2265 // as we don't hold the lock while requesting the trim).
2266 return;
Ian Rogerse1d490c2012-02-03 09:09:07 -08002267 }
Ian Rogers48931882013-01-22 14:35:16 -08002268
Ian Rogers1d54e732013-05-02 21:10:01 -07002269 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002270 ListenForProcessStateChange();
2271
2272 // Trim only if we do not currently care about pause times.
2273 if (!care_about_pause_times_) {
2274 JNIEnv* env = self->GetJniEnv();
2275 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2276 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2277 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2278 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2279 CHECK(!env->ExceptionCheck());
2280 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002281}
2282
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002283bool Heap::IsGCRequestPending() const {
2284 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2285}
2286
Mathieu Chartier590fee92013-09-13 13:46:47 -07002287void Heap::RunFinalization(JNIEnv* env) {
2288 // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
2289 if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
2290 CHECK(WellKnownClasses::java_lang_System != nullptr);
2291 WellKnownClasses::java_lang_System_runFinalization =
2292 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2293 CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
2294 }
2295 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2296 WellKnownClasses::java_lang_System_runFinalization);
2297}
2298
Ian Rogers1eb512d2013-10-18 15:42:20 -07002299void Heap::RegisterNativeAllocation(JNIEnv* env, int bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002300 Thread* self = ThreadForEnv(env);
2301 if (native_need_to_run_finalization_) {
2302 RunFinalization(env);
2303 UpdateMaxNativeFootprint();
2304 native_need_to_run_finalization_ = false;
2305 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002306 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002307 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002308 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
2309 // The second watermark is higher than the gc watermark. If you hit this it means you are
2310 // allocating native objects faster than the GC can keep up with.
2311 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002312 if (WaitForGcToComplete(self) != collector::kGcTypeNone) {
2313 // Just finished a GC, attempt to run finalizers.
2314 RunFinalization(env);
2315 CHECK(!env->ExceptionCheck());
2316 }
2317 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2318 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2319 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
2320 RunFinalization(env);
2321 native_need_to_run_finalization_ = false;
2322 CHECK(!env->ExceptionCheck());
2323 }
2324 // We have just run finalizers, update the native watermark since it is very likely that
2325 // finalizers released native managed allocations.
2326 UpdateMaxNativeFootprint();
2327 } else if (!IsGCRequestPending()) {
2328 if (concurrent_gc_) {
2329 RequestConcurrentGC(self);
2330 } else {
2331 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002332 }
2333 }
2334 }
2335}
2336
Ian Rogers1eb512d2013-10-18 15:42:20 -07002337void Heap::RegisterNativeFree(JNIEnv* env, int bytes) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002338 int expected_size, new_size;
2339 do {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002340 expected_size = native_bytes_allocated_.load();
2341 new_size = expected_size - bytes;
2342 if (UNLIKELY(new_size < 0)) {
2343 ScopedObjectAccess soa(env);
2344 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
2345 StringPrintf("Attempted to free %d native bytes with only %d native bytes "
2346 "registered as allocated", bytes, expected_size).c_str());
2347 break;
2348 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002349 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002350}
2351
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002352int64_t Heap::GetTotalMemory() const {
2353 int64_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002354 for (const auto& space : continuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002355 // Currently don't include the image space.
2356 if (!space->IsImageSpace()) {
2357 ret += space->Size();
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002358 }
2359 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002360 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002361 if (space->IsLargeObjectSpace()) {
2362 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2363 }
2364 }
2365 return ret;
2366}
2367
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002368void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
2369 DCHECK(mod_union_table != nullptr);
2370 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
2371}
2372
Ian Rogers1d54e732013-05-02 21:10:01 -07002373} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002374} // namespace art