blob: 1e3689bbdaaf0d6e3ab43c03392e4cdefcc996c9 [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
Mathieu Chartierb2f99362013-11-20 17:26:00 -080026#include "base/histogram-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070028#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080029#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070030#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070031#include "gc/accounting/atomic_stack.h"
32#include "gc/accounting/card_table-inl.h"
33#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070034#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070035#include "gc/accounting/mod_union_table-inl.h"
36#include "gc/accounting/space_bitmap-inl.h"
37#include "gc/collector/mark_sweep-inl.h"
38#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070039#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/collector/sticky_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070041#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070042#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070043#include "gc/space/image_space.h"
44#include "gc/space/large_object_space.h"
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -070045#include "gc/space/rosalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070046#include "gc/space/space-inl.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070047#include "heap-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070048#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080049#include "invoke_arg_array_builder.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070050#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080051#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/object.h"
53#include "mirror/object-inl.h"
54#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080055#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080056#include "os.h"
Mathieu Chartier0de9f732013-11-22 17:58:48 -080057#include "runtime.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070058#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070059#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070060#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070061#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070062#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070063#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070064
65namespace art {
Mathieu Chartier50482232013-11-21 11:48:14 -080066
67extern void SetQuickAllocEntryPointsAllocator(gc::AllocatorType allocator);
68
Ian Rogers1d54e732013-05-02 21:10:01 -070069namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070070
Mathieu Chartier720ef762013-08-17 14:46:54 -070071static constexpr bool kGCALotMode = false;
72static constexpr size_t kGcAlotInterval = KB;
Ian Rogers1d54e732013-05-02 21:10:01 -070073// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070074static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070075
Mathieu Chartier0051be62012-10-12 17:47:11 -070076Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Ian Rogers8d31bbd2013-10-13 10:44:14 -070077 double target_utilization, size_t capacity, const std::string& image_file_name,
Mathieu Chartier0de9f732013-11-22 17:58:48 -080078 CollectorType collector_type, size_t parallel_gc_threads, size_t conc_gc_threads,
Mathieu Chartier2775ee42013-08-20 17:43:47 -070079 bool low_memory_mode, size_t long_pause_log_threshold, size_t long_gc_log_threshold,
Hiroshi Yamauchi2e899a92013-11-22 16:50:12 -080080 bool ignore_max_footprint)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -080081 : non_moving_space_(nullptr),
Mathieu Chartier0de9f732013-11-22 17:58:48 -080082 concurrent_gc_(collector_type == gc::kCollectorTypeCMS),
83 collector_type_(collector_type),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070084 parallel_gc_threads_(parallel_gc_threads),
85 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070086 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070087 long_pause_log_threshold_(long_pause_log_threshold),
88 long_gc_log_threshold_(long_gc_log_threshold),
89 ignore_max_footprint_(ignore_max_footprint),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070090 have_zygote_space_(false),
Mathieu Chartier39e32612013-11-12 16:28:05 -080091 soft_reference_queue_(this),
92 weak_reference_queue_(this),
93 finalizer_reference_queue_(this),
94 phantom_reference_queue_(this),
95 cleared_references_(this),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080096 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070097 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070098 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080099 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700100 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700101 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700102 native_footprint_gc_watermark_(initial_size),
103 native_footprint_limit_(2 * initial_size),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700104 native_need_to_run_finalization_(false),
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700105 activity_thread_class_(NULL),
106 application_thread_class_(NULL),
107 activity_thread_(NULL),
108 application_thread_(NULL),
109 last_process_state_id_(NULL),
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800110 // Initially assume we perceive jank in case the process state is never updated.
111 process_state_(kProcessStateJankPerceptible),
Mathieu Chartier720ef762013-08-17 14:46:54 -0700112 concurrent_start_bytes_(concurrent_gc_ ? initial_size - kMinConcurrentRemainingBytes
113 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700114 total_bytes_freed_ever_(0),
115 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800116 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700117 native_bytes_allocated_(0),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700118 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700119 verify_missing_card_marks_(false),
120 verify_system_weaks_(false),
121 verify_pre_gc_heap_(false),
122 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700123 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700124 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700125 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700126 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800127 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700128 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
129 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
130 * verification is enabled, we limit the size of allocation stacks to speed up their
131 * searching.
132 */
133 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
Mathieu Chartier590fee92013-09-13 13:46:47 -0700134 : (kDesiredHeapVerification > kVerifyAllFast) ? KB : MB),
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800135 current_allocator_(kMovingCollector ? kAllocatorTypeBumpPointer : kAllocatorTypeFreeList),
136 current_non_moving_allocator_(kAllocatorTypeFreeList),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700137 bump_pointer_space_(nullptr),
138 temp_space_(nullptr),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800139 reference_referent_offset_(0),
140 reference_queue_offset_(0),
141 reference_queueNext_offset_(0),
142 reference_pendingNext_offset_(0),
143 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700144 min_free_(min_free),
145 max_free_(max_free),
146 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700147 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700148 total_allocation_time_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700149 verify_object_mode_(kHeapVerificationNotPermitted),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700150 gc_disable_count_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700151 running_on_valgrind_(RUNNING_ON_VALGRIND) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800152 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800153 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700154 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800155 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
156 // entrypoints.
157 if (!Runtime::Current()->IsZygote()) {
Mathieu Chartier0de9f732013-11-22 17:58:48 -0800158 ChangeCollector(collector_type_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800159 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700160 live_bitmap_.reset(new accounting::HeapBitmap(this));
161 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Ian Rogers30fab402012-01-23 15:43:46 -0800162 // Requested begin for the alloc space, to follow the mapped image and oat files
Mathieu Chartier50482232013-11-21 11:48:14 -0800163 byte* requested_alloc_space_begin = nullptr;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800164 if (!image_file_name.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700165 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str());
Mathieu Chartier50482232013-11-21 11:48:14 -0800166 CHECK(image_space != nullptr) << "Failed to create space for " << image_file_name;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700167 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800168 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
169 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800170 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
171 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700172 if (oat_file_end_addr > requested_alloc_space_begin) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800173 requested_alloc_space_begin = AlignUp(oat_file_end_addr, kPageSize);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700174 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700175 }
176
Mathieu Chartier590fee92013-09-13 13:46:47 -0700177 const char* name = Runtime::Current()->IsZygote() ? "zygote space" : "alloc space";
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700178 if (!kUseRosAlloc) {
179 non_moving_space_ = space::DlMallocSpace::Create(name, initial_size, growth_limit, capacity,
180 requested_alloc_space_begin);
181 } else {
182 non_moving_space_ = space::RosAllocSpace::Create(name, initial_size, growth_limit, capacity,
183 requested_alloc_space_begin);
184 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700185 if (kMovingCollector) {
186 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
187 // TODO: Having 3+ spaces as big as the large heap size can cause virtual memory fragmentation
188 // issues.
189 const size_t bump_pointer_space_size = std::min(non_moving_space_->Capacity(), 128 * MB);
190 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space",
191 bump_pointer_space_size, nullptr);
192 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
193 AddSpace(bump_pointer_space_);
194 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2", bump_pointer_space_size,
195 nullptr);
196 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
197 AddSpace(temp_space_);
198 }
199
200 CHECK(non_moving_space_ != NULL) << "Failed to create non-moving space";
201 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
202 AddSpace(non_moving_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700203
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700204 // Allocate the large object space.
205 const bool kUseFreeListSpaceForLOS = false;
206 if (kUseFreeListSpaceForLOS) {
207 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
208 } else {
209 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
210 }
211 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700212 AddSpace(large_object_space_);
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700213
Ian Rogers1d54e732013-05-02 21:10:01 -0700214 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700215 CHECK(!continuous_spaces_.empty());
216 // Relies on the spaces being sorted.
Ian Rogers1d54e732013-05-02 21:10:01 -0700217 byte* heap_begin = continuous_spaces_.front()->Begin();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700218 byte* heap_end = continuous_spaces_.back()->Limit();
219 size_t heap_capacity = heap_end - heap_begin;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700220
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800221 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700222 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700223 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700224
Mathieu Chartier590fee92013-09-13 13:46:47 -0700225 // Card cache for now since it makes it easier for us to update the references to the copying
226 // spaces.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700227 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier590fee92013-09-13 13:46:47 -0700228 new accounting::ModUnionTableCardCache("Image mod-union table", this, GetImageSpace());
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700229 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
230 AddModUnionTable(mod_union_table);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700231
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700232 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700233 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700234
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800235 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700236 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700237 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
238 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
239 max_allocation_stack_size_));
240 live_stack_.reset(accounting::ObjectStack::Create("live stack",
241 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700242
Mathieu Chartier65db8802012-11-20 12:36:46 -0800243 // It's still too early to take a lock because there are no threads yet, but we can create locks
244 // now. We don't create it earlier to make it clear that you can't use locks during heap
245 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700246 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700247 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
248 *gc_complete_lock_));
Ian Rogers1d54e732013-05-02 21:10:01 -0700249 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800250 last_gc_size_ = GetBytesAllocated();
251
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700252 if (ignore_max_footprint_) {
253 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700254 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700255 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700256 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700257
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800258 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800259 for (size_t i = 0; i < 2; ++i) {
260 const bool concurrent = i != 0;
261 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
262 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
263 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
264 }
265 gc_plan_.push_back(collector::kGcTypeSticky);
266 gc_plan_.push_back(collector::kGcTypePartial);
267 gc_plan_.push_back(collector::kGcTypeFull);
268 if (kMovingCollector) {
269 // TODO: Clean this up.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700270 semi_space_collector_ = new collector::SemiSpace(this);
271 garbage_collectors_.push_back(semi_space_collector_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700272 }
273
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700274 if (running_on_valgrind_) {
Ian Rogersfa824272013-11-05 16:12:57 -0800275 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700276 }
277
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800278 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800279 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700280 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700281}
282
Mathieu Chartier50482232013-11-21 11:48:14 -0800283void Heap::ChangeAllocator(AllocatorType allocator) {
284 DCHECK_NE(allocator, kAllocatorTypeLOS);
285 if (current_allocator_ != allocator) {
286 current_allocator_ = allocator;
287 SetQuickAllocEntryPointsAllocator(current_allocator_);
288 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
289 }
290}
291
Mathieu Chartier590fee92013-09-13 13:46:47 -0700292bool Heap::IsCompilingBoot() const {
293 for (const auto& space : continuous_spaces_) {
294 if (space->IsImageSpace()) {
295 return false;
296 } else if (space->IsZygoteSpace()) {
297 return false;
298 }
299 }
300 return true;
301}
302
303bool Heap::HasImageSpace() const {
304 for (const auto& space : continuous_spaces_) {
305 if (space->IsImageSpace()) {
306 return true;
307 }
308 }
309 return false;
310}
311
312void Heap::IncrementDisableGC(Thread* self) {
313 // Need to do this holding the lock to prevent races where the GC is about to run / running when
314 // we attempt to disable it.
315 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
316 MutexLock mu(self, *gc_complete_lock_);
317 WaitForGcToCompleteLocked(self);
318 ++gc_disable_count_;
319}
320
321void Heap::DecrementDisableGC(Thread* self) {
322 MutexLock mu(self, *gc_complete_lock_);
323 CHECK_GE(gc_disable_count_, 0U);
324 --gc_disable_count_;
325}
326
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800327void Heap::UpdateProcessState(ProcessState process_state) {
328 process_state_ = process_state;
329}
330
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700331void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700332 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
333 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800334 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700335 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700336}
337
Mathieu Chartier590fee92013-09-13 13:46:47 -0700338void Heap::VisitObjects(ObjectVisitorCallback callback, void* arg) {
339 // Visit objects in bump pointer space.
340 Thread* self = Thread::Current();
341 // TODO: Use reference block.
342 std::vector<SirtRef<mirror::Object>*> saved_refs;
343 if (bump_pointer_space_ != nullptr) {
344 // Need to put all these in sirts since the callback may trigger a GC. TODO: Use a better data
345 // structure.
346 mirror::Object* obj = reinterpret_cast<mirror::Object*>(bump_pointer_space_->Begin());
347 const mirror::Object* end = reinterpret_cast<const mirror::Object*>(
348 bump_pointer_space_->End());
349 while (obj < end) {
350 saved_refs.push_back(new SirtRef<mirror::Object>(self, obj));
351 obj = space::BumpPointerSpace::GetNextObject(obj);
352 }
353 }
354 // TODO: Switch to standard begin and end to use ranged a based loop.
355 for (mirror::Object** it = allocation_stack_->Begin(), **end = allocation_stack_->End();
356 it < end; ++it) {
357 mirror::Object* obj = *it;
358 // Objects in the allocation stack might be in a movable space.
359 saved_refs.push_back(new SirtRef<mirror::Object>(self, obj));
360 }
361 GetLiveBitmap()->Walk(callback, arg);
362 for (const auto& ref : saved_refs) {
363 callback(ref->get(), arg);
364 }
365 // Need to free the sirts in reverse order they were allocated.
366 for (size_t i = saved_refs.size(); i != 0; --i) {
367 delete saved_refs[i - 1];
368 }
369}
370
371void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
372 MarkAllocStack(non_moving_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(), stack);
373}
374
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700375void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700376 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700377}
378
Mathieu Chartier590fee92013-09-13 13:46:47 -0700379void Heap::AddSpace(space::Space* space) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700380 DCHECK(space != NULL);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700381 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
382 if (space->IsContinuousSpace()) {
383 DCHECK(!space->IsDiscontinuousSpace());
384 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
385 // Continuous spaces don't necessarily have bitmaps.
386 accounting::SpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
387 accounting::SpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
388 if (live_bitmap != nullptr) {
389 DCHECK(mark_bitmap != nullptr);
390 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
391 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700392 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700393
394 continuous_spaces_.push_back(continuous_space);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700395 if (continuous_space->IsMallocSpace()) {
396 non_moving_space_ = continuous_space->AsMallocSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700397 }
398
399 // Ensure that spaces remain sorted in increasing order of start address.
400 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
401 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
402 return a->Begin() < b->Begin();
403 });
404 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
405 // avoid redundant marking.
406 bool seen_zygote = false, seen_alloc = false;
407 for (const auto& space : continuous_spaces_) {
408 if (space->IsImageSpace()) {
409 CHECK(!seen_zygote);
410 CHECK(!seen_alloc);
411 } else if (space->IsZygoteSpace()) {
412 CHECK(!seen_alloc);
413 seen_zygote = true;
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700414 } else if (space->IsMallocSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700415 seen_alloc = true;
416 }
417 }
418 } else {
419 DCHECK(space->IsDiscontinuousSpace());
420 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
421 DCHECK(discontinuous_space->GetLiveObjects() != nullptr);
422 live_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetLiveObjects());
423 DCHECK(discontinuous_space->GetMarkObjects() != nullptr);
424 mark_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetMarkObjects());
425 discontinuous_spaces_.push_back(discontinuous_space);
426 }
427 if (space->IsAllocSpace()) {
428 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700429 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800430}
431
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700432void Heap::RegisterGCAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700433 if (this != nullptr) {
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700434 gc_memory_overhead_.fetch_add(bytes);
435 }
436}
437
438void Heap::RegisterGCDeAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700439 if (this != nullptr) {
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700440 gc_memory_overhead_.fetch_sub(bytes);
441 }
442}
443
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700444void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700445 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700446 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700447 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800448
449 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800450 uint64_t total_paused_time = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700451 for (const auto& collector : garbage_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800452 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800453 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700454 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800455 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700456 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800457 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
458 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
459 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Mathieu Chartierb2f99362013-11-20 17:26:00 -0800460 Histogram<uint64_t>::CumulativeData cumulative_data;
461 collector->GetPauseHistogram().CreateHistogram(&cumulative_data);
462 collector->GetPauseHistogram().PrintConfidenceIntervals(os, 0.99, cumulative_data);
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700463 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700464 << collector->GetName() << " freed: " << freed_objects
465 << " objects with total size " << PrettySize(freed_bytes) << "\n"
466 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
467 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800468 total_duration += total_ns;
469 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700470 }
471 }
472 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700473 size_t total_objects_allocated = GetObjectsAllocatedEver();
474 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700475 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700476 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700477 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
478 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700479 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700480 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700481 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700482 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700483 os << "Total number of allocations: " << total_objects_allocated << "\n";
484 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700485 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700486 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
487 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
488 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700489 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700490 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
491 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700492 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700493}
494
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800495Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700496 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700497 STLDeleteElements(&garbage_collectors_);
498 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700499 allocation_stack_->Reset();
500 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700501 STLDeleteValues(&mod_union_tables_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700502 STLDeleteElements(&continuous_spaces_);
503 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700504 delete gc_complete_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700505 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700506}
507
Ian Rogers1d54e732013-05-02 21:10:01 -0700508space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
509 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700510 for (const auto& space : continuous_spaces_) {
511 if (space->Contains(obj)) {
512 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700513 }
514 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700515 if (!fail_ok) {
516 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
517 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700518 return NULL;
519}
520
Ian Rogers1d54e732013-05-02 21:10:01 -0700521space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
522 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700523 for (const auto& space : discontinuous_spaces_) {
524 if (space->Contains(obj)) {
525 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700526 }
527 }
528 if (!fail_ok) {
529 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
530 }
531 return NULL;
532}
533
534space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
535 space::Space* result = FindContinuousSpaceFromObject(obj, true);
536 if (result != NULL) {
537 return result;
538 }
539 return FindDiscontinuousSpaceFromObject(obj, true);
540}
541
Mathieu Chartier39e32612013-11-12 16:28:05 -0800542struct SoftReferenceArgs {
543 RootVisitor* is_marked_callback_;
544 RootVisitor* recursive_mark_callback_;
545 void* arg_;
546};
547
548mirror::Object* Heap::PreserveSoftReferenceCallback(mirror::Object* obj, void* arg) {
549 SoftReferenceArgs* args = reinterpret_cast<SoftReferenceArgs*>(arg);
550 // TODO: Not preserve all soft references.
551 return args->recursive_mark_callback_(obj, args->arg_);
552}
553
554// Process reference class instances and schedule finalizations.
555void Heap::ProcessReferences(TimingLogger& timings, bool clear_soft,
556 RootVisitor* is_marked_callback,
557 RootVisitor* recursive_mark_object_callback, void* arg) {
558 // Unless we are in the zygote or required to clear soft references with white references,
559 // preserve some white referents.
560 if (!clear_soft && !Runtime::Current()->IsZygote()) {
561 SoftReferenceArgs soft_reference_args;
562 soft_reference_args.is_marked_callback_ = is_marked_callback;
563 soft_reference_args.recursive_mark_callback_ = recursive_mark_object_callback;
564 soft_reference_args.arg_ = arg;
565 soft_reference_queue_.PreserveSomeSoftReferences(&PreserveSoftReferenceCallback,
566 &soft_reference_args);
567 }
568 timings.StartSplit("ProcessReferences");
569 // Clear all remaining soft and weak references with white referents.
570 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
571 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
572 timings.EndSplit();
573 // Preserve all white objects with finalize methods and schedule them for finalization.
574 timings.StartSplit("EnqueueFinalizerReferences");
575 finalizer_reference_queue_.EnqueueFinalizerReferences(cleared_references_, is_marked_callback,
576 recursive_mark_object_callback, arg);
577 timings.EndSplit();
578 timings.StartSplit("ProcessReferences");
579 // Clear all f-reachable soft and weak references with white referents.
580 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
581 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
582 // Clear all phantom references with white referents.
583 phantom_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
584 // At this point all reference queues other than the cleared references should be empty.
585 DCHECK(soft_reference_queue_.IsEmpty());
586 DCHECK(weak_reference_queue_.IsEmpty());
587 DCHECK(finalizer_reference_queue_.IsEmpty());
588 DCHECK(phantom_reference_queue_.IsEmpty());
589 timings.EndSplit();
590}
591
592bool Heap::IsEnqueued(mirror::Object* ref) const {
593 // Since the references are stored as cyclic lists it means that once enqueued, the pending next
594 // will always be non-null.
595 return ref->GetFieldObject<mirror::Object*>(GetReferencePendingNextOffset(), false) != nullptr;
596}
597
598bool Heap::IsEnqueuable(const mirror::Object* ref) const {
599 DCHECK(ref != nullptr);
600 const mirror::Object* queue =
601 ref->GetFieldObject<mirror::Object*>(GetReferenceQueueOffset(), false);
602 const mirror::Object* queue_next =
603 ref->GetFieldObject<mirror::Object*>(GetReferenceQueueNextOffset(), false);
604 return queue != nullptr && queue_next == nullptr;
605}
606
607// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
608// marked, put it on the appropriate list in the heap for later processing.
609void Heap::DelayReferenceReferent(mirror::Class* klass, mirror::Object* obj,
610 RootVisitor mark_visitor, void* arg) {
611 DCHECK(klass != nullptr);
612 DCHECK(klass->IsReferenceClass());
613 DCHECK(obj != nullptr);
614 mirror::Object* referent = GetReferenceReferent(obj);
615 if (referent != nullptr) {
616 mirror::Object* forward_address = mark_visitor(referent, arg);
617 // Null means that the object is not currently marked.
618 if (forward_address == nullptr) {
619 Thread* self = Thread::Current();
620 // TODO: Remove these locks, and use atomic stacks for storing references?
621 // We need to check that the references haven't already been enqueued since we can end up
622 // scanning the same reference multiple times due to dirty cards.
623 if (klass->IsSoftReferenceClass()) {
624 soft_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
625 } else if (klass->IsWeakReferenceClass()) {
626 weak_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
627 } else if (klass->IsFinalizerReferenceClass()) {
628 finalizer_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
629 } else if (klass->IsPhantomReferenceClass()) {
630 phantom_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
631 } else {
632 LOG(FATAL) << "Invalid reference type " << PrettyClass(klass) << " " << std::hex
633 << klass->GetAccessFlags();
634 }
635 } else if (referent != forward_address) {
636 // Referent is already marked and we need to update it.
637 SetReferenceReferent(obj, forward_address);
638 }
639 }
640}
641
Ian Rogers1d54e732013-05-02 21:10:01 -0700642space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700643 for (const auto& space : continuous_spaces_) {
644 if (space->IsImageSpace()) {
645 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700646 }
647 }
648 return NULL;
649}
650
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700651static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700652 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700653 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700654 size_t chunk_free_bytes = chunk_size - used_bytes;
655 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
656 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700657 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700658}
659
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700660void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, bool large_object_allocation) {
661 std::ostringstream oss;
662 int64_t total_bytes_free = GetFreeMemory();
663 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
664 << " free bytes";
665 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
666 if (!large_object_allocation && total_bytes_free >= byte_count) {
667 size_t max_contiguous_allocation = 0;
668 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700669 if (space->IsMallocSpace()) {
670 // To allow the Walk/InspectAll() to exclusively-lock the mutator
671 // lock, temporarily release the shared access to the mutator
672 // lock here by transitioning to the suspended state.
673 Locks::mutator_lock_->AssertSharedHeld(self);
674 self->TransitionFromRunnableToSuspended(kSuspended);
675 space->AsMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
676 self->TransitionFromSuspendedToRunnable();
677 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700678 }
679 }
680 oss << "; failed due to fragmentation (largest possible contiguous allocation "
681 << max_contiguous_allocation << " bytes)";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700682 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700683 self->ThrowOutOfMemoryError(oss.str().c_str());
684}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700685
Mathieu Chartier590fee92013-09-13 13:46:47 -0700686void Heap::Trim() {
687 uint64_t start_ns = NanoTime();
688 // Trim the managed spaces.
689 uint64_t total_alloc_space_allocated = 0;
690 uint64_t total_alloc_space_size = 0;
691 uint64_t managed_reclaimed = 0;
692 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700693 if (space->IsMallocSpace() && !space->IsZygoteSpace()) {
694 gc::space::MallocSpace* alloc_space = space->AsMallocSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700695 total_alloc_space_size += alloc_space->Size();
696 managed_reclaimed += alloc_space->Trim();
697 }
698 }
699 total_alloc_space_allocated = GetBytesAllocated() - large_object_space_->GetBytesAllocated() -
700 bump_pointer_space_->GetBytesAllocated();
701 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
702 static_cast<float>(total_alloc_space_size);
703 uint64_t gc_heap_end_ns = NanoTime();
704 // Trim the native heap.
705 dlmalloc_trim(0);
706 size_t native_reclaimed = 0;
707 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
708 uint64_t end_ns = NanoTime();
709 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
710 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
711 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
712 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
713 << "%.";
714}
715
716bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
717 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
718 // taking the lock.
719 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -0700720 return true;
721 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700722 return IsAligned<kObjectAlignment>(obj) && IsHeapAddress(obj);
723}
724
725bool Heap::IsHeapAddress(const mirror::Object* obj) const {
726 if (kMovingCollector && bump_pointer_space_->HasAddress(obj)) {
727 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700728 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700729 // TODO: This probably doesn't work for large objects.
730 return FindSpaceFromObject(obj, true) != nullptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700731}
732
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700733bool Heap::IsLiveObjectLocked(const mirror::Object* obj, bool search_allocation_stack,
734 bool search_live_stack, bool sorted) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700735 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700736 if (obj == nullptr || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700737 return false;
738 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700739 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
740 space::DiscontinuousSpace* d_space = NULL;
741 if (c_space != NULL) {
742 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700743 return true;
744 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700745 } else if (bump_pointer_space_->Contains(obj) || temp_space_->Contains(obj)) {
746 return true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700747 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700748 d_space = FindDiscontinuousSpaceFromObject(obj, true);
749 if (d_space != NULL) {
750 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700751 return true;
752 }
753 }
754 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700755 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700756 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
757 if (i > 0) {
758 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -0700759 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700760 if (search_allocation_stack) {
761 if (sorted) {
762 if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
763 return true;
764 }
765 } else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
766 return true;
767 }
768 }
769
770 if (search_live_stack) {
771 if (sorted) {
772 if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
773 return true;
774 }
775 } else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
776 return true;
777 }
778 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700779 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700780 // We need to check the bitmaps again since there is a race where we mark something as live and
781 // then clear the stack containing it.
782 if (c_space != NULL) {
783 if (c_space->GetLiveBitmap()->Test(obj)) {
784 return true;
785 }
786 } else {
787 d_space = FindDiscontinuousSpaceFromObject(obj, true);
788 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
789 return true;
790 }
791 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700792 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700793}
794
Ian Rogers04d7aa92013-03-16 14:29:17 -0700795void Heap::VerifyObjectImpl(const mirror::Object* obj) {
796 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700797 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700798 return;
799 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700800 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700801}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700802
Mathieu Chartier590fee92013-09-13 13:46:47 -0700803void Heap::DumpSpaces(std::ostream& stream) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700804 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700805 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
806 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700807 stream << space << " " << *space << "\n";
808 if (live_bitmap != nullptr) {
809 stream << live_bitmap << " " << *live_bitmap << "\n";
810 }
811 if (mark_bitmap != nullptr) {
812 stream << mark_bitmap << " " << *mark_bitmap << "\n";
813 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700814 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700815 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700816 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700817 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700818}
819
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800820void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700821 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
822 // Ignore early dawn of the universe verifications.
823 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.load()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800824 return;
825 }
826 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
827 mirror::Object::ClassOffset().Int32Value();
828 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
829 if (UNLIKELY(c == NULL)) {
830 LOG(FATAL) << "Null class in object: " << obj;
831 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
832 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
833 }
834 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
835 // Note: we don't use the accessors here as they have internal sanity checks
836 // that we don't want to run
837 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
838 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
839 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
840 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
841 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700842
Mathieu Chartier590fee92013-09-13 13:46:47 -0700843 if (verify_object_mode_ > kVerifyAllFast) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800844 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
845 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700846 if (!IsLiveObjectLocked(obj)) {
847 DumpSpaces();
848 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700849 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700850 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700851 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
852 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700853 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700854}
855
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800856void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700857 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700858 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700859}
860
861void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700862 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700863 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700864}
865
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700866void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700867 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700868 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700869
870 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700871 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700872 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700873 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700874
875 // TODO: Do this concurrently.
876 RuntimeStats* global_stats = Runtime::Current()->GetStats();
877 global_stats->freed_objects += freed_objects;
878 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700879 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700880}
881
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800882mirror::Object* Heap::AllocateInternalWithGc(Thread* self, AllocatorType allocator,
Mathieu Chartier720ef762013-08-17 14:46:54 -0700883 size_t alloc_size, size_t* bytes_allocated) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800884 mirror::Object* ptr = nullptr;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700885 // The allocation failed. If the GC is running, block until it completes, and then retry the
886 // allocation.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700887 collector::GcType last_gc = WaitForGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700888 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700889 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800890 ptr = TryToAllocate<true>(self, allocator, alloc_size, false, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700891 }
892
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700893 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800894 for (collector::GcType gc_type : gc_plan_) {
895 if (ptr != nullptr) {
896 break;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700897 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800898 // Attempt to run the collector, if we succeed, re-try the allocation.
899 if (CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700900 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800901 ptr = TryToAllocate<true>(self, allocator, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700902 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700903 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700904 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800905 if (ptr == nullptr) {
906 // Try harder, growing the heap if necessary.
907 ptr = TryToAllocate<true>(self, allocator, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700908 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800909 if (ptr == nullptr) {
910 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
911 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
912 // VM spec requires that all SoftReferences have been collected and cleared before throwing
913 // OOME.
914 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
915 << " allocation";
916 // TODO: Run finalization, but this may cause more allocations to occur.
917 // We don't need a WaitForGcToComplete here either.
918 DCHECK(!gc_plan_.empty());
919 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
920 ptr = TryToAllocate<true>(self, allocator, alloc_size, true, bytes_allocated);
921 if (ptr == nullptr) {
922 ThrowOutOfMemoryError(self, alloc_size, false);
923 }
924 }
925 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700926}
927
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700928void Heap::SetTargetHeapUtilization(float target) {
929 DCHECK_GT(target, 0.0f); // asserted in Java code
930 DCHECK_LT(target, 1.0f);
931 target_utilization_ = target;
932}
933
Ian Rogers1d54e732013-05-02 21:10:01 -0700934size_t Heap::GetObjectsAllocated() const {
935 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700936 for (space::AllocSpace* space : alloc_spaces_) {
937 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -0700938 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700939 return total;
940}
941
Ian Rogers1d54e732013-05-02 21:10:01 -0700942size_t Heap::GetObjectsAllocatedEver() const {
943 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700944 for (space::AllocSpace* space : alloc_spaces_) {
945 total += space->GetTotalObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -0700946 }
947 return total;
948}
949
950size_t Heap::GetBytesAllocatedEver() const {
951 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700952 for (space::AllocSpace* space : alloc_spaces_) {
953 total += space->GetTotalBytesAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -0700954 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700955 return total;
956}
957
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700958class InstanceCounter {
959 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800960 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700961 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800962 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700963 }
964
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800965 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800966 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800967 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800968 if (use_is_assignable_from_) {
969 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
970 ++counts_[i];
971 }
972 } else {
973 if (instance_class == classes_[i]) {
974 ++counts_[i];
975 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700976 }
977 }
978 }
979
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700980 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800981 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800982 bool use_is_assignable_from_;
983 uint64_t* const counts_;
984
985 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700986};
987
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800988void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800989 uint64_t* counts) {
990 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
991 // is empty, so the live bitmap is the only place we need to look.
992 Thread* self = Thread::Current();
993 self->TransitionFromRunnableToSuspended(kNative);
994 CollectGarbage(false);
995 self->TransitionFromSuspendedToRunnable();
996
997 InstanceCounter counter(classes, use_is_assignable_from, counts);
998 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700999 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001000}
1001
Elliott Hughes3b78c942013-01-15 17:35:41 -08001002class InstanceCollector {
1003 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001004 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001005 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1006 : class_(c), max_count_(max_count), instances_(instances) {
1007 }
1008
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001009 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1010 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001011 if (instance_class == class_) {
1012 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001013 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001014 }
1015 }
1016 }
1017
1018 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001019 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001020 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001021 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001022
1023 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1024};
1025
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001026void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1027 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001028 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1029 // is empty, so the live bitmap is the only place we need to look.
1030 Thread* self = Thread::Current();
1031 self->TransitionFromRunnableToSuspended(kNative);
1032 CollectGarbage(false);
1033 self->TransitionFromSuspendedToRunnable();
1034
1035 InstanceCollector collector(c, max_count, instances);
1036 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1037 GetLiveBitmap()->Visit(collector);
1038}
1039
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001040class ReferringObjectsFinder {
1041 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001042 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1043 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001044 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1045 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1046 }
1047
1048 // For bitmap Visit.
1049 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1050 // annotalysis on visitors.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001051 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
1052 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(o), *this, true);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001053 }
1054
1055 // For MarkSweep::VisitObjectReferences.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001056 void operator()(mirror::Object* referrer, mirror::Object* object,
Brian Carlstromdf629502013-07-17 22:39:56 -07001057 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001058 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001059 referring_objects_.push_back(referrer);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001060 }
1061 }
1062
1063 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001064 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001065 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001066 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001067
1068 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1069};
1070
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001071void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1072 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001073 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1074 // is empty, so the live bitmap is the only place we need to look.
1075 Thread* self = Thread::Current();
1076 self->TransitionFromRunnableToSuspended(kNative);
1077 CollectGarbage(false);
1078 self->TransitionFromSuspendedToRunnable();
1079
1080 ReferringObjectsFinder finder(o, max_count, referring_objects);
1081 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1082 GetLiveBitmap()->Visit(finder);
1083}
1084
Ian Rogers30fab402012-01-23 15:43:46 -08001085void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001086 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1087 // last GC will not have necessarily been cleared.
Ian Rogers1d54e732013-05-02 21:10:01 -07001088 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001089}
1090
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001091void Heap::ChangeCollector(CollectorType collector_type) {
1092 switch (collector_type) {
1093 case kCollectorTypeSS: {
1094 ChangeAllocator(kAllocatorTypeBumpPointer);
1095 break;
1096 }
1097 case kCollectorTypeMS:
1098 // Fall-through.
1099 case kCollectorTypeCMS: {
1100 ChangeAllocator(kAllocatorTypeFreeList);
1101 break;
Mathieu Chartier7410f292013-11-24 13:17:35 -08001102 default:
1103 LOG(FATAL) << "Unimplemented";
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001104 }
1105 }
1106}
1107
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001108void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001109 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -07001110 Thread* self = Thread::Current();
1111 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001112 // Try to see if we have any Zygote spaces.
1113 if (have_zygote_space_) {
1114 return;
1115 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001116 VLOG(heap) << "Starting PreZygoteFork";
1117 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1118 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
1119 // Trim the pages at the end of the non moving space.
1120 non_moving_space_->Trim();
1121 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier50482232013-11-21 11:48:14 -08001122 // Change the allocator to the post zygote one.
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001123 ChangeCollector(collector_type_);
Mathieu Chartier50482232013-11-21 11:48:14 -08001124 // TODO: Delete bump_pointer_space_ and temp_pointer_space_?
Mathieu Chartier590fee92013-09-13 13:46:47 -07001125 if (semi_space_collector_ != nullptr) {
Mathieu Chartier50482232013-11-21 11:48:14 -08001126 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001127 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1128 non_moving_space_->Limit());
1129 // Compact the bump pointer space to a new zygote bump pointer space.
1130 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1131 Compact(&target_space, bump_pointer_space_);
1132 CHECK_EQ(temp_space_->GetBytesAllocated(), 0U);
1133 total_objects_freed_ever_ += semi_space_collector_->GetFreedObjects();
1134 total_bytes_freed_ever_ += semi_space_collector_->GetFreedBytes();
1135 // Update the end and write out image.
1136 non_moving_space_->SetEnd(target_space.End());
1137 non_moving_space_->SetLimit(target_space.Limit());
1138 accounting::SpaceBitmap* bitmap = non_moving_space_->GetLiveBitmap();
1139 // Record the allocations in the bitmap.
1140 VLOG(heap) << "Recording zygote allocations";
1141 mirror::Object* obj = reinterpret_cast<mirror::Object*>(target_space.Begin());
1142 const mirror::Object* end = reinterpret_cast<const mirror::Object*>(target_space.End());
1143 while (obj < end) {
1144 bitmap->Set(obj);
1145 obj = space::BumpPointerSpace::GetNextObject(obj);
1146 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001147 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001148 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
1149 // the remaining available heap memory.
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001150 space::MallocSpace* zygote_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001151 non_moving_space_ = zygote_space->CreateZygoteSpace("alloc space");
1152 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -07001153 // Change the GC retention policy of the zygote space to only collect when full.
1154 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001155 AddSpace(non_moving_space_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001156 have_zygote_space_ = true;
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001157 zygote_space->InvalidateAllocator();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001158 // Create the zygote space mod union table.
1159 accounting::ModUnionTable* mod_union_table =
1160 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1161 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1162 AddModUnionTable(mod_union_table);
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001163 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001164 for (const auto& collector : garbage_collectors_) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001165 collector->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001166 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001167}
1168
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001169void Heap::FlushAllocStack() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001170 MarkAllocStack(non_moving_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001171 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001172 allocation_stack_->Reset();
1173}
1174
Ian Rogers1d54e732013-05-02 21:10:01 -07001175void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1176 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001177 mirror::Object** limit = stack->End();
1178 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1179 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001180 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001181 if (LIKELY(bitmap->HasAddress(obj))) {
1182 bitmap->Set(obj);
1183 } else {
1184 large_objects->Set(obj);
1185 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001186 }
1187}
1188
Mathieu Chartier590fee92013-09-13 13:46:47 -07001189const char* PrettyCause(GcCause cause) {
1190 switch (cause) {
1191 case kGcCauseForAlloc: return "Alloc";
1192 case kGcCauseBackground: return "Background";
1193 case kGcCauseExplicit: return "Explicit";
1194 default:
1195 LOG(FATAL) << "Unreachable";
1196 }
1197 return "";
1198}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001199
Mathieu Chartier590fee92013-09-13 13:46:47 -07001200void Heap::SwapSemiSpaces() {
1201 // Swap the spaces so we allocate into the space which we just evacuated.
1202 std::swap(bump_pointer_space_, temp_space_);
1203}
1204
1205void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
1206 space::ContinuousMemMapAllocSpace* source_space) {
1207 CHECK(kMovingCollector);
Mathieu Chartier50482232013-11-21 11:48:14 -08001208 CHECK_NE(target_space, source_space) << "In-place compaction currently unsupported";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001209 if (target_space != source_space) {
1210 semi_space_collector_->SetFromSpace(source_space);
1211 semi_space_collector_->SetToSpace(target_space);
1212 semi_space_collector_->Run(false);
1213 }
1214}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001215
Ian Rogers1d54e732013-05-02 21:10:01 -07001216collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1217 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001218 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001219 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001220 // If the heap can't run the GC, silently fail and return that no GC was run.
1221 switch (gc_type) {
1222 case collector::kGcTypeSticky: {
1223 const size_t alloc_space_size = non_moving_space_->Size();
1224 if (alloc_space_size < min_alloc_space_size_for_sticky_gc_ ||
1225 non_moving_space_->Capacity() - alloc_space_size < min_remaining_space_for_sticky_gc_) {
1226 return collector::kGcTypeNone;
1227 }
1228 break;
1229 }
1230 case collector::kGcTypePartial: {
1231 if (!have_zygote_space_) {
1232 return collector::kGcTypeNone;
1233 }
1234 break;
1235 }
1236 default: {
1237 // Other GC types don't have any special cases which makes them not runnable. The main case
1238 // here is full GC.
1239 }
1240 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001241 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001242 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001243 if (self->IsHandlingStackOverflow()) {
1244 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1245 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001246 {
1247 gc_complete_lock_->AssertNotHeld(self);
1248 MutexLock mu(self, *gc_complete_lock_);
1249 // Ensure there is only one GC at a time.
1250 WaitForGcToCompleteLocked(self);
1251 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1252 // Not doing at the moment to ensure soft references are cleared.
1253 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
1254 if (gc_disable_count_ != 0) {
1255 LOG(WARNING) << "Skipping GC due to disable count " << gc_disable_count_;
1256 return collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001257 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001258 is_gc_running_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001259 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001260 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
1261 ++runtime->GetStats()->gc_for_alloc_count;
1262 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001263 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001264 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001265 uint64_t gc_start_size = GetBytesAllocated();
1266 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001267 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001268 // Back to back GCs can cause 0 ms of wait time in between GC invocations.
1269 if (LIKELY(ms_delta != 0)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001270 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001271 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1272 }
1273
Ian Rogers1d54e732013-05-02 21:10:01 -07001274 DCHECK_LT(gc_type, collector::kGcTypeMax);
1275 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001276
Mathieu Chartier590fee92013-09-13 13:46:47 -07001277 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08001278 // TODO: Clean this up.
1279 if (current_allocator_ == kAllocatorTypeBumpPointer) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001280 gc_type = semi_space_collector_->GetGcType();
1281 CHECK_EQ(temp_space_->GetObjectsAllocated(), 0U);
1282 semi_space_collector_->SetFromSpace(bump_pointer_space_);
1283 semi_space_collector_->SetToSpace(temp_space_);
1284 mprotect(temp_space_->Begin(), temp_space_->Capacity(), PROT_READ | PROT_WRITE);
Mathieu Chartier50482232013-11-21 11:48:14 -08001285 collector = semi_space_collector_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001286 gc_type = collector::kGcTypeFull;
Mathieu Chartier50482232013-11-21 11:48:14 -08001287 } else if (current_allocator_ == kAllocatorTypeFreeList) {
1288 for (const auto& cur_collector : garbage_collectors_) {
1289 if (cur_collector->IsConcurrent() == concurrent_gc_ &&
1290 cur_collector->GetGcType() == gc_type) {
1291 collector = cur_collector;
1292 break;
1293 }
1294 }
1295 } else {
1296 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001297 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001298 CHECK(collector != NULL)
1299 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1300 << " and type=" << gc_type;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001301
Mathieu Chartier590fee92013-09-13 13:46:47 -07001302 ATRACE_BEGIN(StringPrintf("%s %s GC", PrettyCause(gc_cause), collector->GetName()).c_str());
1303
1304 collector->Run(clear_soft_references);
Ian Rogers1d54e732013-05-02 21:10:01 -07001305 total_objects_freed_ever_ += collector->GetFreedObjects();
1306 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001307
Mathieu Chartier39e32612013-11-12 16:28:05 -08001308 // Enqueue cleared references.
1309 EnqueueClearedReferences();
1310
Mathieu Chartier590fee92013-09-13 13:46:47 -07001311 // Grow the heap so that we know when to perform the next GC.
1312 GrowForUtilization(gc_type, collector->GetDurationNs());
1313
Mathieu Chartierca2a24d2013-11-25 15:12:12 -08001314 if (CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001315 const size_t duration = collector->GetDurationNs();
1316 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1317 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001318 bool was_slow = duration > long_gc_log_threshold_ ||
1319 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001320 if (!was_slow) {
1321 for (uint64_t pause : pauses) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001322 was_slow = was_slow || pause > long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001323 }
1324 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001325 if (was_slow) {
1326 const size_t percent_free = GetPercentFree();
1327 const size_t current_heap_size = GetBytesAllocated();
1328 const size_t total_memory = GetTotalMemory();
1329 std::ostringstream pause_string;
1330 for (size_t i = 0; i < pauses.size(); ++i) {
1331 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1332 << ((i != pauses.size() - 1) ? ", " : "");
1333 }
1334 LOG(INFO) << gc_cause << " " << collector->GetName()
1335 << " GC freed " << collector->GetFreedObjects() << "("
1336 << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1337 << collector->GetFreedLargeObjects() << "("
1338 << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1339 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1340 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1341 << " total " << PrettyDuration((duration / 1000) * 1000);
1342 if (VLOG_IS_ON(heap)) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001343 LOG(INFO) << Dumpable<TimingLogger>(collector->GetTimings());
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001344 }
1345 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001346 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001347
Ian Rogers15bf2d32012-08-28 17:33:04 -07001348 {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001349 MutexLock mu(self, *gc_complete_lock_);
1350 is_gc_running_ = false;
1351 last_gc_type_ = gc_type;
1352 // Wake anyone who may have been waiting for the GC to complete.
1353 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001354 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001355
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001356 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001357
1358 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001359 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001360 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001361}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001362
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001363static mirror::Object* RootMatchesObjectVisitor(mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001364 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001365 if (root == obj) {
1366 LOG(INFO) << "Object " << obj << " is a root";
1367 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001368 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001369}
1370
1371class ScanVisitor {
1372 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001373 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001374 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001375 }
1376};
1377
Ian Rogers1d54e732013-05-02 21:10:01 -07001378// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001379class VerifyReferenceVisitor {
1380 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001381 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001382 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001383 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001384
1385 bool Failed() const {
1386 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001387 }
1388
1389 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001390 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001391 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1392 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001393 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001394 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001395 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1396 accounting::CardTable* card_table = heap_->GetCardTable();
1397 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1398 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001399 if (!failed_) {
1400 // Print message on only on first failure to prevent spam.
1401 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
1402 failed_ = true;
1403 }
1404 if (obj != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001405 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001406 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
1407 << offset << "\n card value = " << static_cast<int>(*card_addr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001408 if (heap_->IsValidObjectAddress(obj->GetClass())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001409 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1410 } else {
1411 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
1412 }
1413
1414 // Attmept to find the class inside of the recently freed objects.
1415 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001416 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
1417 space::MallocSpace* space = ref_space->AsMallocSpace();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001418 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
1419 if (ref_class != nullptr) {
1420 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
1421 << PrettyClass(ref_class);
1422 } else {
1423 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
1424 }
1425 }
1426
Mathieu Chartier590fee92013-09-13 13:46:47 -07001427 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001428 ref->GetClass()->IsClass()) {
1429 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1430 } else {
1431 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
1432 << ") is not a valid heap address";
1433 }
1434
Ian Rogers1d54e732013-05-02 21:10:01 -07001435 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1436 void* cover_begin = card_table->AddrFromCard(card_addr);
1437 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1438 accounting::CardTable::kCardSize);
1439 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1440 << "-" << cover_end;
1441 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001442
Ian Rogers1d54e732013-05-02 21:10:01 -07001443 // Print out how the object is live.
1444 if (bitmap != NULL && bitmap->Test(obj)) {
1445 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1446 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001447 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001448 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1449 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001450 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001451 LOG(ERROR) << "Object " << obj << " found in live stack";
1452 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001453 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1454 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
1455 }
1456 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1457 LOG(ERROR) << "Ref " << ref << " found in live stack";
1458 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001459 // Attempt to see if the card table missed the reference.
1460 ScanVisitor scan_visitor;
1461 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1462 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001463 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001464
1465 // Search to see if any of the roots reference our object.
1466 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1467 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1468
1469 // Search to see if any of the roots reference our reference.
1470 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1471 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1472 } else {
1473 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001474 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001475 }
1476 }
1477
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001478 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001479 return heap_->IsLiveObjectLocked(obj, true, false, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001480 }
1481
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001482 static mirror::Object* VerifyRoots(mirror::Object* root, void* arg) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001483 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001484 (*visitor)(nullptr, root, MemberOffset(0), true);
1485 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001486 }
1487
1488 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001489 Heap* const heap_;
1490 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001491};
1492
Ian Rogers1d54e732013-05-02 21:10:01 -07001493// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001494class VerifyObjectVisitor {
1495 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001496 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001497
Mathieu Chartier590fee92013-09-13 13:46:47 -07001498 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001499 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001500 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1501 // be live or else how did we find it in the live bitmap?
1502 VerifyReferenceVisitor visitor(heap_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001503 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001504 collector::MarkSweep::VisitObjectReferences(obj, visitor, true);
1505 if (obj->GetClass()->IsReferenceClass()) {
1506 visitor(obj, heap_->GetReferenceReferent(obj), MemberOffset(0), false);
1507 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001508 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001509 }
1510
Mathieu Chartier590fee92013-09-13 13:46:47 -07001511 static void VisitCallback(mirror::Object* obj, void* arg)
1512 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1513 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
1514 visitor->operator()(obj);
1515 }
1516
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001517 bool Failed() const {
1518 return failed_;
1519 }
1520
1521 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001522 Heap* const heap_;
1523 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001524};
1525
1526// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001527bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001528 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001529 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001530 allocation_stack_->Sort();
1531 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001532 VerifyObjectVisitor visitor(this);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001533 // Verify objects in the allocation stack since these will be objects which were:
1534 // 1. Allocated prior to the GC (pre GC verification).
1535 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001536 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001537 // pointing to dead objects if they are not reachable.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001538 VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
1539 // Verify the roots:
1540 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001541 if (visitor.Failed()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001542 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001543 for (const auto& table_pair : mod_union_tables_) {
1544 accounting::ModUnionTable* mod_union_table = table_pair.second;
1545 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
1546 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001547 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001548 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001549 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001550 return true;
1551}
1552
1553class VerifyReferenceCardVisitor {
1554 public:
1555 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1556 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1557 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001558 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001559 }
1560
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001561 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1562 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001563 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1564 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001565 // Filter out class references since changing an object's class does not mark the card as dirty.
1566 // Also handles large objects, since the only reference they hold is a class reference.
1567 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001568 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001569 // If the object is not dirty and it is referencing something in the live stack other than
1570 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001571 if (!card_table->AddrIsInCardTable(obj)) {
1572 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1573 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001574 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001575 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1576 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001577 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001578 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1579 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001580 LOG(ERROR) << "Object " << obj << " found in live stack";
1581 }
1582 if (heap_->GetLiveBitmap()->Test(obj)) {
1583 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1584 }
1585 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1586 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1587
1588 // Print which field of the object is dead.
1589 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001590 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001591 CHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001592 const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
1593 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001594 CHECK(fields != NULL);
1595 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001596 const mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001597 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1598 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1599 << PrettyField(cur);
1600 break;
1601 }
1602 }
1603 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001604 const mirror::ObjectArray<mirror::Object>* object_array =
1605 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001606 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1607 if (object_array->Get(i) == ref) {
1608 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1609 }
1610 }
1611 }
1612
1613 *failed_ = true;
1614 }
1615 }
1616 }
1617 }
1618
1619 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001620 Heap* const heap_;
1621 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001622};
1623
1624class VerifyLiveStackReferences {
1625 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001626 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001627 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001628 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001629
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001630 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001631 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1632 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001633 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(obj), visitor, true);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001634 }
1635
1636 bool Failed() const {
1637 return failed_;
1638 }
1639
1640 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001641 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001642 bool failed_;
1643};
1644
1645bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001646 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001647
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001648 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001649 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001650 VerifyLiveStackReferences visitor(this);
1651 GetLiveBitmap()->Visit(visitor);
1652
1653 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001654 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001655 visitor(*it);
1656 }
1657
1658 if (visitor.Failed()) {
1659 DumpSpaces();
1660 return false;
1661 }
1662 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001663}
1664
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001665void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001666 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001667}
1668
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001669accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
1670 auto it = mod_union_tables_.find(space);
1671 if (it == mod_union_tables_.end()) {
1672 return nullptr;
1673 }
1674 return it->second;
1675}
1676
Ian Rogers5fe9af72013-11-14 00:17:20 -08001677void Heap::ProcessCards(TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001678 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001679 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001680 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
1681 if (table != nullptr) {
1682 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
1683 "ImageModUnionClearCards";
Ian Rogers5fe9af72013-11-14 00:17:20 -08001684 TimingLogger::ScopedSplit split(name, &timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001685 table->ClearCards();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001686 } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001687 TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001688 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1689 // were dirty before the GC started.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001690 // TODO: Don't need to use atomic.
1691 // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
1692 // roots and then we scan / update mod union tables after. We will always scan either card.//
1693 // If we end up with the non aged card, we scan it it in the pause.
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001694 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001695 }
1696 }
1697}
1698
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001699static mirror::Object* IdentityCallback(mirror::Object* obj, void*) {
1700 return obj;
1701}
1702
Ian Rogers1d54e732013-05-02 21:10:01 -07001703void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001704 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1705 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001706
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001707 if (verify_pre_gc_heap_) {
1708 thread_list->SuspendAll();
1709 {
1710 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1711 if (!VerifyHeapReferences()) {
1712 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1713 }
1714 }
1715 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001716 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001717
1718 // Check that all objects which reference things in the live stack are on dirty cards.
1719 if (verify_missing_card_marks_) {
1720 thread_list->SuspendAll();
1721 {
1722 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1723 SwapStacks();
1724 // Sort the live stack so that we can quickly binary search it later.
1725 if (!VerifyMissingCardMarks()) {
1726 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1727 }
1728 SwapStacks();
1729 }
1730 thread_list->ResumeAll();
1731 }
1732
1733 if (verify_mod_union_table_) {
1734 thread_list->SuspendAll();
1735 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001736 for (const auto& table_pair : mod_union_tables_) {
1737 accounting::ModUnionTable* mod_union_table = table_pair.second;
1738 mod_union_table->UpdateAndMarkReferences(IdentityCallback, nullptr);
1739 mod_union_table->Verify();
1740 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001741 thread_list->ResumeAll();
1742 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001743}
1744
Ian Rogers1d54e732013-05-02 21:10:01 -07001745void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001746 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1747 // reachable objects.
1748 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001749 Thread* self = Thread::Current();
1750 CHECK_NE(self->GetState(), kRunnable);
Ian Rogers1d54e732013-05-02 21:10:01 -07001751 {
1752 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1753 // Swapping bound bitmaps does nothing.
1754 gc->SwapBitmaps();
1755 if (!VerifyHeapReferences()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001756 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
Ian Rogers1d54e732013-05-02 21:10:01 -07001757 }
1758 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001759 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001760 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001761}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001762
Ian Rogers1d54e732013-05-02 21:10:01 -07001763void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001764 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001765 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001766 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001767 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001768 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001769 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001770}
1771
Mathieu Chartier590fee92013-09-13 13:46:47 -07001772collector::GcType Heap::WaitForGcToComplete(Thread* self) {
1773 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1774 MutexLock mu(self, *gc_complete_lock_);
1775 return WaitForGcToCompleteLocked(self);
1776}
1777
1778collector::GcType Heap::WaitForGcToCompleteLocked(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001779 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001780 uint64_t wait_start = NanoTime();
1781 while (is_gc_running_) {
1782 ATRACE_BEGIN("GC: Wait For Completion");
1783 // We must wait, change thread state then sleep on gc_complete_cond_;
1784 gc_complete_cond_->Wait(self);
1785 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001786 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001787 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001788 uint64_t wait_time = NanoTime() - wait_start;
1789 total_wait_time_ += wait_time;
1790 if (wait_time > long_pause_log_threshold_) {
1791 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time);
1792 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001793 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001794}
1795
Elliott Hughesc967f782012-04-16 10:23:15 -07001796void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001797 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001798 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001799 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001800}
1801
1802size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001803 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001804}
1805
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001806void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001807 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001808 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001809 << PrettySize(GetMaxMemory());
1810 max_allowed_footprint = GetMaxMemory();
1811 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001812 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001813}
1814
Mathieu Chartier590fee92013-09-13 13:46:47 -07001815bool Heap::IsMovableObject(const mirror::Object* obj) const {
1816 if (kMovingCollector) {
1817 DCHECK(!IsInTempSpace(obj));
1818 if (bump_pointer_space_->HasAddress(obj)) {
1819 return true;
1820 }
1821 }
1822 return false;
1823}
1824
1825bool Heap::IsInTempSpace(const mirror::Object* obj) const {
1826 if (temp_space_->HasAddress(obj) && !temp_space_->Contains(obj)) {
1827 return true;
1828 }
1829 return false;
1830}
1831
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001832void Heap::UpdateMaxNativeFootprint() {
1833 size_t native_size = native_bytes_allocated_;
1834 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1835 size_t target_size = native_size / GetTargetHeapUtilization();
1836 if (target_size > native_size + max_free_) {
1837 target_size = native_size + max_free_;
1838 } else if (target_size < native_size + min_free_) {
1839 target_size = native_size + min_free_;
1840 }
1841 native_footprint_gc_watermark_ = target_size;
1842 native_footprint_limit_ = 2 * target_size - native_size;
1843}
1844
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001845void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001846 // We know what our utilization is at this moment.
1847 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001848 const size_t bytes_allocated = GetBytesAllocated();
1849 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001850 last_gc_time_ns_ = NanoTime();
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001851 size_t target_size;
1852 if (gc_type != collector::kGcTypeSticky) {
1853 // Grow the heap for non sticky GC.
1854 target_size = bytes_allocated / GetTargetHeapUtilization();
1855 if (target_size > bytes_allocated + max_free_) {
1856 target_size = bytes_allocated + max_free_;
1857 } else if (target_size < bytes_allocated + min_free_) {
1858 target_size = bytes_allocated + min_free_;
1859 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001860 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001861 next_gc_type_ = collector::kGcTypeSticky;
1862 } else {
1863 // Based on how close the current heap size is to the target size, decide
1864 // whether or not to do a partial or sticky GC next.
1865 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1866 next_gc_type_ = collector::kGcTypeSticky;
1867 } else {
1868 next_gc_type_ = collector::kGcTypePartial;
1869 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001870 // If we have freed enough memory, shrink the heap back down.
1871 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1872 target_size = bytes_allocated + max_free_;
1873 } else {
1874 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1875 }
1876 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001877 if (!ignore_max_footprint_) {
1878 SetIdealFootprint(target_size);
Mathieu Chartier50482232013-11-21 11:48:14 -08001879 if (concurrent_gc_ && AllocatorHasConcurrentGC(current_allocator_)) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001880 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001881 // Calculate the estimated GC duration.
1882 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1883 // Estimate how many remaining bytes we will have when we need to start the next GC.
1884 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1885 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1886 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1887 // A never going to happen situation that from the estimated allocation rate we will exceed
1888 // the applications entire footprint with the given estimated allocation rate. Schedule
1889 // another GC straight away.
1890 concurrent_start_bytes_ = bytes_allocated;
1891 } else {
1892 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1893 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1894 // right away.
Mathieu Chartier50482232013-11-21 11:48:14 -08001895 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
1896 bytes_allocated);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001897 }
1898 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1899 DCHECK_LE(max_allowed_footprint_, growth_limit_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001900 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001901 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001902}
1903
jeffhaoc1160702011-10-27 15:48:45 -07001904void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001905 growth_limit_ = capacity_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001906 non_moving_space_->ClearGrowthLimit();
jeffhaoc1160702011-10-27 15:48:45 -07001907}
1908
Elliott Hughesadb460d2011-10-05 17:02:34 -07001909void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartier50482232013-11-21 11:48:14 -08001910 MemberOffset reference_queue_offset,
1911 MemberOffset reference_queueNext_offset,
1912 MemberOffset reference_pendingNext_offset,
1913 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001914 reference_referent_offset_ = reference_referent_offset;
1915 reference_queue_offset_ = reference_queue_offset;
1916 reference_queueNext_offset_ = reference_queueNext_offset;
1917 reference_pendingNext_offset_ = reference_pendingNext_offset;
1918 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1919 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1920 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1921 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1922 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1923 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1924}
1925
Mathieu Chartier590fee92013-09-13 13:46:47 -07001926void Heap::SetReferenceReferent(mirror::Object* reference, mirror::Object* referent) {
1927 DCHECK(reference != NULL);
1928 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1929 reference->SetFieldObject(reference_referent_offset_, referent, true);
1930}
1931
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001932mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001933 DCHECK(reference != NULL);
1934 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001935 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001936}
1937
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001938void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001939 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001940 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001941 ArgArray arg_array(NULL, 0);
1942 arg_array.Append(reinterpret_cast<uint32_t>(object));
1943 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001944 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001945}
1946
Mathieu Chartier39e32612013-11-12 16:28:05 -08001947void Heap::EnqueueClearedReferences() {
1948 if (!cleared_references_.IsEmpty()) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001949 // When a runtime isn't started there are no reference queues to care about so ignore.
1950 if (LIKELY(Runtime::Current()->IsStarted())) {
1951 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001952 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001953 ArgArray arg_array(NULL, 0);
Mathieu Chartier39e32612013-11-12 16:28:05 -08001954 arg_array.Append(reinterpret_cast<uint32_t>(cleared_references_.GetList()));
Jeff Hao5d917302013-02-27 17:57:33 -08001955 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001956 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001957 }
Mathieu Chartier39e32612013-11-12 16:28:05 -08001958 cleared_references_.Clear();
Elliott Hughesadb460d2011-10-05 17:02:34 -07001959 }
1960}
1961
Ian Rogers1f539342012-10-03 21:09:42 -07001962void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001963 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001964 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001965 DCHECK(concurrent_gc_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001966 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
1967 self->IsHandlingStackOverflow()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001968 return;
1969 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001970 // We already have a request pending, no reason to start more until we update
1971 // concurrent_start_bytes_.
1972 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers120f1c72012-09-28 17:17:10 -07001973 JNIEnv* env = self->GetJniEnv();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001974 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
1975 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001976 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1977 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001978 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001979}
1980
Ian Rogers81d425b2012-09-27 16:03:43 -07001981void Heap::ConcurrentGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001982 if (Runtime::Current()->IsShuttingDown(self)) {
1983 return;
Mathieu Chartier2542d662012-06-21 17:14:11 -07001984 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001985 // Wait for any GCs currently running to finish.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001986 if (WaitForGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08001987 // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
1988 // instead. E.g. can't do partial, so do full instead.
1989 if (CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false) ==
1990 collector::kGcTypeNone) {
1991 for (collector::GcType gc_type : gc_plan_) {
1992 // Attempt to run the collector, if we succeed, we are done.
1993 if (gc_type > next_gc_type_ &&
1994 CollectGarbageInternal(gc_type, kGcCauseBackground, false) != collector::kGcTypeNone) {
1995 break;
1996 }
1997 }
1998 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001999 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002000}
2001
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002002void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08002003 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
2004 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
2005 // a space it will hold its lock and can become a cause of jank.
2006 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
2007 // forking.
2008
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002009 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2010 // because that only marks object heads, so a large array looks like lots of empty space. We
2011 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2012 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2013 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2014 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08002015 uint64_t ms_time = MilliTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002016 // Don't bother trimming the alloc space if a heap trim occurred in the last two seconds.
2017 if (ms_time - last_trim_time_ms_ < 2 * 1000) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002018 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002019 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002020
2021 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002022 Runtime* runtime = Runtime::Current();
2023 if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self)) {
2024 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2025 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2026 // as we don't hold the lock while requesting the trim).
2027 return;
Ian Rogerse1d490c2012-02-03 09:09:07 -08002028 }
Ian Rogers48931882013-01-22 14:35:16 -08002029
Ian Rogers1d54e732013-05-02 21:10:01 -07002030 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002031
2032 // Trim only if we do not currently care about pause times.
Mathieu Chartierca2a24d2013-11-25 15:12:12 -08002033 if (!CareAboutPauseTimes()) {
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002034 JNIEnv* env = self->GetJniEnv();
2035 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2036 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2037 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2038 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2039 CHECK(!env->ExceptionCheck());
2040 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002041}
2042
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002043void Heap::RevokeThreadLocalBuffers(Thread* thread) {
2044 non_moving_space_->RevokeThreadLocalBuffers(thread);
2045}
2046
2047void Heap::RevokeAllThreadLocalBuffers() {
2048 non_moving_space_->RevokeAllThreadLocalBuffers();
2049}
2050
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002051bool Heap::IsGCRequestPending() const {
2052 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2053}
2054
Mathieu Chartier590fee92013-09-13 13:46:47 -07002055void Heap::RunFinalization(JNIEnv* env) {
2056 // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
2057 if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
2058 CHECK(WellKnownClasses::java_lang_System != nullptr);
2059 WellKnownClasses::java_lang_System_runFinalization =
2060 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2061 CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
2062 }
2063 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2064 WellKnownClasses::java_lang_System_runFinalization);
2065}
2066
Ian Rogers1eb512d2013-10-18 15:42:20 -07002067void Heap::RegisterNativeAllocation(JNIEnv* env, int bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002068 Thread* self = ThreadForEnv(env);
2069 if (native_need_to_run_finalization_) {
2070 RunFinalization(env);
2071 UpdateMaxNativeFootprint();
2072 native_need_to_run_finalization_ = false;
2073 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002074 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002075 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002076 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002077 collector::GcType gc_type = have_zygote_space_ ? collector::kGcTypePartial :
2078 collector::kGcTypeFull;
2079
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002080 // The second watermark is higher than the gc watermark. If you hit this it means you are
2081 // allocating native objects faster than the GC can keep up with.
2082 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002083 if (WaitForGcToComplete(self) != collector::kGcTypeNone) {
2084 // Just finished a GC, attempt to run finalizers.
2085 RunFinalization(env);
2086 CHECK(!env->ExceptionCheck());
2087 }
2088 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2089 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002090 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002091 RunFinalization(env);
2092 native_need_to_run_finalization_ = false;
2093 CHECK(!env->ExceptionCheck());
2094 }
2095 // We have just run finalizers, update the native watermark since it is very likely that
2096 // finalizers released native managed allocations.
2097 UpdateMaxNativeFootprint();
2098 } else if (!IsGCRequestPending()) {
Mathieu Chartier50482232013-11-21 11:48:14 -08002099 if (concurrent_gc_ && AllocatorHasConcurrentGC(current_allocator_)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002100 RequestConcurrentGC(self);
2101 } else {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002102 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002103 }
2104 }
2105 }
2106}
2107
Ian Rogers1eb512d2013-10-18 15:42:20 -07002108void Heap::RegisterNativeFree(JNIEnv* env, int bytes) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002109 int expected_size, new_size;
2110 do {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002111 expected_size = native_bytes_allocated_.load();
2112 new_size = expected_size - bytes;
2113 if (UNLIKELY(new_size < 0)) {
2114 ScopedObjectAccess soa(env);
2115 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
2116 StringPrintf("Attempted to free %d native bytes with only %d native bytes "
2117 "registered as allocated", bytes, expected_size).c_str());
2118 break;
2119 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002120 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002121}
2122
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002123int64_t Heap::GetTotalMemory() const {
2124 int64_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002125 for (const auto& space : continuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002126 // Currently don't include the image space.
2127 if (!space->IsImageSpace()) {
2128 ret += space->Size();
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002129 }
2130 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002131 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002132 if (space->IsLargeObjectSpace()) {
2133 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2134 }
2135 }
2136 return ret;
2137}
2138
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002139void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
2140 DCHECK(mod_union_table != nullptr);
2141 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
2142}
2143
Ian Rogers1d54e732013-05-02 21:10:01 -07002144} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002145} // namespace art