blob: 70df3d3133d08e96bc36794c4096d46483a27fd1 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070018
Mathieu Chartier752a0e62013-06-27 11:03:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <cutils/trace.h>
Brian Carlstrom5643b782012-02-05 12:32:53 -080021
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070023#include <vector>
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070024#include <valgrind.h>
Carl Shapiro58551df2011-07-24 03:09:51 -070025
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070027#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080028#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070029#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070030#include "gc/accounting/atomic_stack.h"
31#include "gc/accounting/card_table-inl.h"
32#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070033#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070034#include "gc/accounting/mod_union_table-inl.h"
35#include "gc/accounting/space_bitmap-inl.h"
36#include "gc/collector/mark_sweep-inl.h"
37#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070038#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/collector/sticky_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070040#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070041#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070042#include "gc/space/image_space.h"
43#include "gc/space/large_object_space.h"
44#include "gc/space/space-inl.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070045#include "heap-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070046#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080047#include "invoke_arg_array_builder.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070048#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080049#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "mirror/object.h"
51#include "mirror/object-inl.h"
52#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080053#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080054#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070055#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070056#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070057#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070058#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070059#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070060#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070061
62namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070063namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070064
Mathieu Chartier720ef762013-08-17 14:46:54 -070065static constexpr bool kGCALotMode = false;
66static constexpr size_t kGcAlotInterval = KB;
67static constexpr bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070068// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070069static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070070
Mathieu Chartier0051be62012-10-12 17:47:11 -070071Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Ian Rogers8d31bbd2013-10-13 10:44:14 -070072 double target_utilization, size_t capacity, const std::string& image_file_name,
Mathieu Chartier2775ee42013-08-20 17:43:47 -070073 bool concurrent_gc, size_t parallel_gc_threads, size_t conc_gc_threads,
74 bool low_memory_mode, size_t long_pause_log_threshold, size_t long_gc_log_threshold,
75 bool ignore_max_footprint)
Mathieu Chartier590fee92013-09-13 13:46:47 -070076 : non_moving_space_(NULL),
77 concurrent_gc_(!kMovingCollector && concurrent_gc),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070078 parallel_gc_threads_(parallel_gc_threads),
79 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070080 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070081 long_pause_log_threshold_(long_pause_log_threshold),
82 long_gc_log_threshold_(long_gc_log_threshold),
83 ignore_max_footprint_(ignore_max_footprint),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070084 have_zygote_space_(false),
Mathieu Chartier94c32c52013-08-09 11:14:04 -070085 soft_ref_queue_lock_(NULL),
86 weak_ref_queue_lock_(NULL),
87 finalizer_ref_queue_lock_(NULL),
88 phantom_ref_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080089 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070090 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070091 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080092 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070093 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070094 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070095 native_footprint_gc_watermark_(initial_size),
96 native_footprint_limit_(2 * initial_size),
Mathieu Chartier590fee92013-09-13 13:46:47 -070097 native_need_to_run_finalization_(false),
Mathieu Chartierc39e3422013-08-07 16:41:36 -070098 activity_thread_class_(NULL),
99 application_thread_class_(NULL),
100 activity_thread_(NULL),
101 application_thread_(NULL),
102 last_process_state_id_(NULL),
103 // Initially care about pauses in case we never get notified of process states, or if the JNI
104 // code becomes broken.
105 care_about_pause_times_(true),
Mathieu Chartier720ef762013-08-17 14:46:54 -0700106 concurrent_start_bytes_(concurrent_gc_ ? initial_size - kMinConcurrentRemainingBytes
107 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700108 total_bytes_freed_ever_(0),
109 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800110 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700111 native_bytes_allocated_(0),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700112 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700113 verify_missing_card_marks_(false),
114 verify_system_weaks_(false),
115 verify_pre_gc_heap_(false),
116 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700117 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700118 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700119 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700120 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800121 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700122 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
123 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
124 * verification is enabled, we limit the size of allocation stacks to speed up their
125 * searching.
126 */
127 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
Mathieu Chartier590fee92013-09-13 13:46:47 -0700128 : (kDesiredHeapVerification > kVerifyAllFast) ? KB : MB),
129 bump_pointer_space_(nullptr),
130 temp_space_(nullptr),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800131 reference_referent_offset_(0),
132 reference_queue_offset_(0),
133 reference_queueNext_offset_(0),
134 reference_pendingNext_offset_(0),
135 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700136 min_free_(min_free),
137 max_free_(max_free),
138 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700139 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700140 total_allocation_time_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700141 verify_object_mode_(kHeapVerificationNotPermitted),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700142 gc_disable_count_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700143 running_on_valgrind_(RUNNING_ON_VALGRIND) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800144 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800145 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700146 }
147
Ian Rogers1d54e732013-05-02 21:10:01 -0700148 live_bitmap_.reset(new accounting::HeapBitmap(this));
149 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700150
Ian Rogers30fab402012-01-23 15:43:46 -0800151 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700152 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800153 if (!image_file_name.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700154 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700155 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700156 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800157 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
158 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800159 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
160 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700161 if (oat_file_end_addr > requested_alloc_space_begin) {
162 requested_alloc_space_begin =
163 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
164 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700165 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700166 }
167
Mathieu Chartier590fee92013-09-13 13:46:47 -0700168 const char* name = Runtime::Current()->IsZygote() ? "zygote space" : "alloc space";
169 non_moving_space_ = space::DlMallocSpace::Create(name, initial_size, growth_limit, capacity,
170 requested_alloc_space_begin);
171
172 if (kMovingCollector) {
173 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
174 // TODO: Having 3+ spaces as big as the large heap size can cause virtual memory fragmentation
175 // issues.
176 const size_t bump_pointer_space_size = std::min(non_moving_space_->Capacity(), 128 * MB);
177 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space",
178 bump_pointer_space_size, nullptr);
179 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
180 AddSpace(bump_pointer_space_);
181 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2", bump_pointer_space_size,
182 nullptr);
183 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
184 AddSpace(temp_space_);
185 }
186
187 CHECK(non_moving_space_ != NULL) << "Failed to create non-moving space";
188 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
189 AddSpace(non_moving_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700190
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700191 // Allocate the large object space.
192 const bool kUseFreeListSpaceForLOS = false;
193 if (kUseFreeListSpaceForLOS) {
194 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
195 } else {
196 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
197 }
198 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700199 AddSpace(large_object_space_);
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700200
Ian Rogers1d54e732013-05-02 21:10:01 -0700201 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700202 CHECK(!continuous_spaces_.empty());
203 // Relies on the spaces being sorted.
Ian Rogers1d54e732013-05-02 21:10:01 -0700204 byte* heap_begin = continuous_spaces_.front()->Begin();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700205 byte* heap_end = continuous_spaces_.back()->Limit();
206 size_t heap_capacity = heap_end - heap_begin;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700207
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800208 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700209 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700210 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700211
Mathieu Chartier590fee92013-09-13 13:46:47 -0700212 // Card cache for now since it makes it easier for us to update the references to the copying
213 // spaces.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700214 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier590fee92013-09-13 13:46:47 -0700215 new accounting::ModUnionTableCardCache("Image mod-union table", this, GetImageSpace());
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700216 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
217 AddModUnionTable(mod_union_table);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700218
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700219 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700220 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700221
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800222 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700223 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700224 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
225 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
226 max_allocation_stack_size_));
227 live_stack_.reset(accounting::ObjectStack::Create("live stack",
228 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700229
Mathieu Chartier65db8802012-11-20 12:36:46 -0800230 // It's still too early to take a lock because there are no threads yet, but we can create locks
231 // now. We don't create it earlier to make it clear that you can't use locks during heap
232 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700233 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700234 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
235 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700236
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700237 // Create the reference queue locks, this is required so for parallel object scanning in the GC.
238 soft_ref_queue_lock_ = new Mutex("Soft reference queue lock");
239 weak_ref_queue_lock_ = new Mutex("Weak reference queue lock");
240 finalizer_ref_queue_lock_ = new Mutex("Finalizer reference queue lock");
241 phantom_ref_queue_lock_ = new Mutex("Phantom reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700242
Ian Rogers1d54e732013-05-02 21:10:01 -0700243 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800244 last_gc_size_ = GetBytesAllocated();
245
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700246 if (ignore_max_footprint_) {
247 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700248 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700249 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700250 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700251
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800252 // Create our garbage collectors.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700253 if (!kMovingCollector) {
254 for (size_t i = 0; i < 2; ++i) {
255 const bool concurrent = i != 0;
256 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
257 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
258 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
259 }
260 } else {
261 semi_space_collector_ = new collector::SemiSpace(this);
262 garbage_collectors_.push_back(semi_space_collector_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700263 }
264
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700265 if (running_on_valgrind_) {
Ian Rogersfa824272013-11-05 16:12:57 -0800266 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700267 }
268
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800269 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800270 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700271 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700272}
273
Mathieu Chartier590fee92013-09-13 13:46:47 -0700274bool Heap::IsCompilingBoot() const {
275 for (const auto& space : continuous_spaces_) {
276 if (space->IsImageSpace()) {
277 return false;
278 } else if (space->IsZygoteSpace()) {
279 return false;
280 }
281 }
282 return true;
283}
284
285bool Heap::HasImageSpace() const {
286 for (const auto& space : continuous_spaces_) {
287 if (space->IsImageSpace()) {
288 return true;
289 }
290 }
291 return false;
292}
293
294void Heap::IncrementDisableGC(Thread* self) {
295 // Need to do this holding the lock to prevent races where the GC is about to run / running when
296 // we attempt to disable it.
297 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
298 MutexLock mu(self, *gc_complete_lock_);
299 WaitForGcToCompleteLocked(self);
300 ++gc_disable_count_;
301}
302
303void Heap::DecrementDisableGC(Thread* self) {
304 MutexLock mu(self, *gc_complete_lock_);
305 CHECK_GE(gc_disable_count_, 0U);
306 --gc_disable_count_;
307}
308
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700309void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700310 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
311 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800312 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700313 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700314}
315
Mathieu Chartier590fee92013-09-13 13:46:47 -0700316void Heap::VisitObjects(ObjectVisitorCallback callback, void* arg) {
317 // Visit objects in bump pointer space.
318 Thread* self = Thread::Current();
319 // TODO: Use reference block.
320 std::vector<SirtRef<mirror::Object>*> saved_refs;
321 if (bump_pointer_space_ != nullptr) {
322 // Need to put all these in sirts since the callback may trigger a GC. TODO: Use a better data
323 // structure.
324 mirror::Object* obj = reinterpret_cast<mirror::Object*>(bump_pointer_space_->Begin());
325 const mirror::Object* end = reinterpret_cast<const mirror::Object*>(
326 bump_pointer_space_->End());
327 while (obj < end) {
328 saved_refs.push_back(new SirtRef<mirror::Object>(self, obj));
329 obj = space::BumpPointerSpace::GetNextObject(obj);
330 }
331 }
332 // TODO: Switch to standard begin and end to use ranged a based loop.
333 for (mirror::Object** it = allocation_stack_->Begin(), **end = allocation_stack_->End();
334 it < end; ++it) {
335 mirror::Object* obj = *it;
336 // Objects in the allocation stack might be in a movable space.
337 saved_refs.push_back(new SirtRef<mirror::Object>(self, obj));
338 }
339 GetLiveBitmap()->Walk(callback, arg);
340 for (const auto& ref : saved_refs) {
341 callback(ref->get(), arg);
342 }
343 // Need to free the sirts in reverse order they were allocated.
344 for (size_t i = saved_refs.size(); i != 0; --i) {
345 delete saved_refs[i - 1];
346 }
347}
348
349void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
350 MarkAllocStack(non_moving_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(), stack);
351}
352
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700353void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700354 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700355}
356
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700357static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700358 DCHECK(out_value != NULL);
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700359 jfieldID field = env->GetStaticFieldID(clz, name, "I");
360 if (field == NULL) {
361 env->ExceptionClear();
362 return false;
363 }
364 *out_value = env->GetStaticIntField(clz, field);
365 return true;
366}
367
368void Heap::ListenForProcessStateChange() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700369 VLOG(heap) << "Heap notified of process state change";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700370
371 Thread* self = Thread::Current();
372 JNIEnvExt* env = self->GetJniEnv();
373
374 if (!have_zygote_space_) {
375 return;
376 }
377
378 if (activity_thread_class_ == NULL) {
379 jclass clz = env->FindClass("android/app/ActivityThread");
380 if (clz == NULL) {
381 env->ExceptionClear();
382 LOG(WARNING) << "Could not find activity thread class in process state change";
383 return;
384 }
385 activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
386 }
387
388 if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
389 jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
390 "currentActivityThread",
391 "()Landroid/app/ActivityThread;");
392 if (current_activity_method == NULL) {
393 env->ExceptionClear();
394 LOG(WARNING) << "Could not get method for currentActivityThread";
395 return;
396 }
397
398 jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
399 if (obj == NULL) {
400 env->ExceptionClear();
401 LOG(WARNING) << "Could not get current activity";
402 return;
403 }
404 activity_thread_ = env->NewGlobalRef(obj);
405 }
406
407 if (process_state_cares_about_pause_time_.empty()) {
408 // Just attempt to do this the first time.
409 jclass clz = env->FindClass("android/app/ActivityManager");
410 if (clz == NULL) {
411 LOG(WARNING) << "Activity manager class is null";
412 return;
413 }
414 ScopedLocalRef<jclass> activity_manager(env, clz);
415 std::vector<const char*> care_about_pauses;
416 care_about_pauses.push_back("PROCESS_STATE_TOP");
417 care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
418 // Attempt to read the constants and classify them as whether or not we care about pause times.
419 for (size_t i = 0; i < care_about_pauses.size(); ++i) {
420 int process_state = 0;
421 if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
422 process_state_cares_about_pause_time_.insert(process_state);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700423 VLOG(heap) << "Adding process state " << process_state
424 << " to set of states which care about pause time";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700425 }
426 }
427 }
428
429 if (application_thread_class_ == NULL) {
430 jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
431 if (clz == NULL) {
432 env->ExceptionClear();
433 LOG(WARNING) << "Could not get application thread class";
434 return;
435 }
436 application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
437 last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
438 if (last_process_state_id_ == NULL) {
439 env->ExceptionClear();
440 LOG(WARNING) << "Could not get last process state member";
441 return;
442 }
443 }
444
445 if (application_thread_class_ != NULL && application_thread_ == NULL) {
446 jmethodID get_application_thread =
447 env->GetMethodID(activity_thread_class_, "getApplicationThread",
448 "()Landroid/app/ActivityThread$ApplicationThread;");
449 if (get_application_thread == NULL) {
450 LOG(WARNING) << "Could not get method ID for get application thread";
451 return;
452 }
453
454 jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
455 if (obj == NULL) {
456 LOG(WARNING) << "Could not get application thread";
457 return;
458 }
459
460 application_thread_ = env->NewGlobalRef(obj);
461 }
462
463 if (application_thread_ != NULL && last_process_state_id_ != NULL) {
464 int process_state = env->GetIntField(application_thread_, last_process_state_id_);
465 env->ExceptionClear();
466
467 care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
468 process_state_cares_about_pause_time_.end();
469
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700470 VLOG(heap) << "New process state " << process_state
471 << " care about pauses " << care_about_pause_times_;
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700472 }
Mathieu Chartier82353312013-07-18 10:47:51 -0700473}
474
Mathieu Chartier590fee92013-09-13 13:46:47 -0700475void Heap::AddSpace(space::Space* space) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700476 DCHECK(space != NULL);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700477 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
478 if (space->IsContinuousSpace()) {
479 DCHECK(!space->IsDiscontinuousSpace());
480 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
481 // Continuous spaces don't necessarily have bitmaps.
482 accounting::SpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
483 accounting::SpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
484 if (live_bitmap != nullptr) {
485 DCHECK(mark_bitmap != nullptr);
486 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
487 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700488 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700489
490 continuous_spaces_.push_back(continuous_space);
491 if (continuous_space->IsDlMallocSpace()) {
492 non_moving_space_ = continuous_space->AsDlMallocSpace();
493 }
494
495 // Ensure that spaces remain sorted in increasing order of start address.
496 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
497 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
498 return a->Begin() < b->Begin();
499 });
500 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
501 // avoid redundant marking.
502 bool seen_zygote = false, seen_alloc = false;
503 for (const auto& space : continuous_spaces_) {
504 if (space->IsImageSpace()) {
505 CHECK(!seen_zygote);
506 CHECK(!seen_alloc);
507 } else if (space->IsZygoteSpace()) {
508 CHECK(!seen_alloc);
509 seen_zygote = true;
510 } else if (space->IsDlMallocSpace()) {
511 seen_alloc = true;
512 }
513 }
514 } else {
515 DCHECK(space->IsDiscontinuousSpace());
516 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
517 DCHECK(discontinuous_space->GetLiveObjects() != nullptr);
518 live_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetLiveObjects());
519 DCHECK(discontinuous_space->GetMarkObjects() != nullptr);
520 mark_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetMarkObjects());
521 discontinuous_spaces_.push_back(discontinuous_space);
522 }
523 if (space->IsAllocSpace()) {
524 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700525 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800526}
527
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700528void Heap::RegisterGCAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700529 if (this != nullptr) {
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700530 gc_memory_overhead_.fetch_add(bytes);
531 }
532}
533
534void Heap::RegisterGCDeAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700535 if (this != nullptr) {
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700536 gc_memory_overhead_.fetch_sub(bytes);
537 }
538}
539
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700540void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700541 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700542 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700543 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800544
545 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800546 uint64_t total_paused_time = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700547 for (const auto& collector : garbage_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800548 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800549 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700550 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800551 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700552 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800553 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
554 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
555 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700556 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
557 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
558 << collector->GetName() << " freed: " << freed_objects
559 << " objects with total size " << PrettySize(freed_bytes) << "\n"
560 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
561 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800562 total_duration += total_ns;
563 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700564 }
565 }
566 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700567 size_t total_objects_allocated = GetObjectsAllocatedEver();
568 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700569 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700570 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700571 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
572 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700573 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700574 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700575 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700576 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700577 os << "Total number of allocations: " << total_objects_allocated << "\n";
578 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700579 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700580 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
581 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
582 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700583 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700584 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
585 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700586 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700587}
588
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800589Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700590 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700591 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700592 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700593 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700594 STLDeleteElements(&garbage_collectors_);
595 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700596 allocation_stack_->Reset();
597 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700598 STLDeleteValues(&mod_union_tables_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700599 STLDeleteElements(&continuous_spaces_);
600 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700601 delete gc_complete_lock_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700602 delete soft_ref_queue_lock_;
603 delete weak_ref_queue_lock_;
604 delete finalizer_ref_queue_lock_;
605 delete phantom_ref_queue_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700606 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700607}
608
Ian Rogers1d54e732013-05-02 21:10:01 -0700609space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
610 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700611 for (const auto& space : continuous_spaces_) {
612 if (space->Contains(obj)) {
613 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700614 }
615 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700616 if (!fail_ok) {
617 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
618 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700619 return NULL;
620}
621
Ian Rogers1d54e732013-05-02 21:10:01 -0700622space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
623 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700624 for (const auto& space : discontinuous_spaces_) {
625 if (space->Contains(obj)) {
626 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700627 }
628 }
629 if (!fail_ok) {
630 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
631 }
632 return NULL;
633}
634
635space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
636 space::Space* result = FindContinuousSpaceFromObject(obj, true);
637 if (result != NULL) {
638 return result;
639 }
640 return FindDiscontinuousSpaceFromObject(obj, true);
641}
642
643space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700644 for (const auto& space : continuous_spaces_) {
645 if (space->IsImageSpace()) {
646 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700647 }
648 }
649 return NULL;
650}
651
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700652static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700653 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700654 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700655 size_t chunk_free_bytes = chunk_size - used_bytes;
656 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
657 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700658 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700659}
660
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700661void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, bool large_object_allocation) {
662 std::ostringstream oss;
663 int64_t total_bytes_free = GetFreeMemory();
664 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
665 << " free bytes";
666 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
667 if (!large_object_allocation && total_bytes_free >= byte_count) {
668 size_t max_contiguous_allocation = 0;
669 for (const auto& space : continuous_spaces_) {
670 if (space->IsDlMallocSpace()) {
671 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
672 }
673 }
674 oss << "; failed due to fragmentation (largest possible contiguous allocation "
675 << max_contiguous_allocation << " bytes)";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700676 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700677 self->ThrowOutOfMemoryError(oss.str().c_str());
678}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700679
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700680inline bool Heap::TryAllocLargeObjectInstrumented(Thread* self, mirror::Class* c, size_t byte_count,
681 mirror::Object** obj_ptr, size_t* bytes_allocated) {
682 bool large_object_allocation = ShouldAllocLargeObject(c, byte_count);
Ian Rogers333cf1b2013-07-24 11:57:02 -0700683 if (UNLIKELY(large_object_allocation)) {
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700684 mirror::Object* obj = AllocateInstrumented(self, large_object_space_, byte_count, bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700685 // Make sure that our large object didn't get placed anywhere within the space interval or else
686 // it breaks the immune range.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700687 DCHECK(obj == nullptr ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700688 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
689 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700690 *obj_ptr = obj;
691 }
692 return large_object_allocation;
693}
694
Mathieu Chartier590fee92013-09-13 13:46:47 -0700695mirror::Object* Heap::AllocMovableObjectInstrumented(Thread* self, mirror::Class* c,
696 size_t byte_count) {
697 DebugCheckPreconditionsForAllocObject(c, byte_count);
698 mirror::Object* obj;
699 AllocationTimer alloc_timer(this, &obj);
700 byte_count = RoundUp(byte_count, 8);
701 if (UNLIKELY(IsOutOfMemoryOnAllocation(byte_count, false))) {
702 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, false);
703 if (UNLIKELY(IsOutOfMemoryOnAllocation(byte_count, true))) {
704 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
705 }
706 }
707 obj = bump_pointer_space_->AllocNonvirtual(byte_count);
708 if (LIKELY(obj != NULL)) {
709 obj->SetClass(c);
710 DCHECK(!obj->IsClass());
711 // Record allocation after since we want to use the atomic add for the atomic fence to guard
712 // the SetClass since we do not want the class to appear NULL in another thread.
713 num_bytes_allocated_.fetch_add(byte_count);
714 if (Runtime::Current()->HasStatsEnabled()) {
715 RuntimeStats* thread_stats = Thread::Current()->GetStats();
716 ++thread_stats->allocated_objects;
717 thread_stats->allocated_bytes += byte_count;
718 RuntimeStats* global_stats = Runtime::Current()->GetStats();
719 ++global_stats->allocated_objects;
720 global_stats->allocated_bytes += byte_count;
721 }
722 if (Dbg::IsAllocTrackingEnabled()) {
723 Dbg::RecordAllocation(c, byte_count);
724 }
725 if (kDesiredHeapVerification > kNoHeapVerification) {
726 VerifyObject(obj);
727 }
728 } else {
729 ThrowOutOfMemoryError(self, byte_count, false);
730 }
731 if (kIsDebugBuild) {
732 self->VerifyStack();
733 }
734 return obj;
735}
736
737mirror::Object* Heap::AllocNonMovableObjectInstrumented(Thread* self, mirror::Class* c,
738 size_t byte_count) {
739 DebugCheckPreconditionsForAllocObject(c, byte_count);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700740 mirror::Object* obj;
741 size_t bytes_allocated;
742 AllocationTimer alloc_timer(this, &obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700743 bool large_object_allocation = TryAllocLargeObjectInstrumented(self, c, byte_count, &obj,
744 &bytes_allocated);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700745 if (LIKELY(!large_object_allocation)) {
746 // Non-large object allocation.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700747 obj = AllocateInstrumented(self, non_moving_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700748 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700749 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700750 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700751 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700752 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700753 // Record allocation after since we want to use the atomic add for the atomic fence to guard
754 // the SetClass since we do not want the class to appear NULL in another thread.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700755 size_t new_num_bytes_allocated = RecordAllocationInstrumented(bytes_allocated, obj);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700756 if (Dbg::IsAllocTrackingEnabled()) {
757 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700758 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700759 CheckConcurrentGC(self, new_num_bytes_allocated, obj);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700760 if (kDesiredHeapVerification > kNoHeapVerification) {
761 VerifyObject(obj);
762 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700763 } else {
764 ThrowOutOfMemoryError(self, byte_count, large_object_allocation);
Carl Shapiro58551df2011-07-24 03:09:51 -0700765 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700766 if (kIsDebugBuild) {
767 self->VerifyStack();
768 }
769 return obj;
Carl Shapiro58551df2011-07-24 03:09:51 -0700770}
771
Mathieu Chartier590fee92013-09-13 13:46:47 -0700772void Heap::Trim() {
773 uint64_t start_ns = NanoTime();
774 // Trim the managed spaces.
775 uint64_t total_alloc_space_allocated = 0;
776 uint64_t total_alloc_space_size = 0;
777 uint64_t managed_reclaimed = 0;
778 for (const auto& space : continuous_spaces_) {
779 if (space->IsDlMallocSpace() && !space->IsZygoteSpace()) {
780 gc::space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
781 total_alloc_space_size += alloc_space->Size();
782 managed_reclaimed += alloc_space->Trim();
783 }
784 }
785 total_alloc_space_allocated = GetBytesAllocated() - large_object_space_->GetBytesAllocated() -
786 bump_pointer_space_->GetBytesAllocated();
787 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
788 static_cast<float>(total_alloc_space_size);
789 uint64_t gc_heap_end_ns = NanoTime();
790 // Trim the native heap.
791 dlmalloc_trim(0);
792 size_t native_reclaimed = 0;
793 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
794 uint64_t end_ns = NanoTime();
795 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
796 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
797 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
798 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
799 << "%.";
800}
801
802bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
803 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
804 // taking the lock.
805 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -0700806 return true;
807 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700808 return IsAligned<kObjectAlignment>(obj) && IsHeapAddress(obj);
809}
810
811bool Heap::IsHeapAddress(const mirror::Object* obj) const {
812 if (kMovingCollector && bump_pointer_space_->HasAddress(obj)) {
813 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700814 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700815 // TODO: This probably doesn't work for large objects.
816 return FindSpaceFromObject(obj, true) != nullptr;
Elliott Hughesa2501992011-08-26 19:39:54 -0700817}
818
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700819bool Heap::IsLiveObjectLocked(const mirror::Object* obj, bool search_allocation_stack,
820 bool search_live_stack, bool sorted) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700821 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700822 if (obj == nullptr || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700823 return false;
824 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700825 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
826 space::DiscontinuousSpace* d_space = NULL;
827 if (c_space != NULL) {
828 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700829 return true;
830 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700831 } else if (bump_pointer_space_->Contains(obj) || temp_space_->Contains(obj)) {
832 return true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700833 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700834 d_space = FindDiscontinuousSpaceFromObject(obj, true);
835 if (d_space != NULL) {
836 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700837 return true;
838 }
839 }
840 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700841 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700842 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
843 if (i > 0) {
844 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -0700845 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700846
847 if (search_allocation_stack) {
848 if (sorted) {
849 if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
850 return true;
851 }
852 } else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
853 return true;
854 }
855 }
856
857 if (search_live_stack) {
858 if (sorted) {
859 if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
860 return true;
861 }
862 } else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
863 return true;
864 }
865 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700866 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700867 // We need to check the bitmaps again since there is a race where we mark something as live and
868 // then clear the stack containing it.
869 if (c_space != NULL) {
870 if (c_space->GetLiveBitmap()->Test(obj)) {
871 return true;
872 }
873 } else {
874 d_space = FindDiscontinuousSpaceFromObject(obj, true);
875 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
876 return true;
877 }
878 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700879 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700880}
881
Ian Rogers04d7aa92013-03-16 14:29:17 -0700882void Heap::VerifyObjectImpl(const mirror::Object* obj) {
883 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700884 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700885 return;
886 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700887 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700888}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700889
Mathieu Chartier590fee92013-09-13 13:46:47 -0700890void Heap::DumpSpaces(std::ostream& stream) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700891 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700892 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
893 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700894 stream << space << " " << *space << "\n";
895 if (live_bitmap != nullptr) {
896 stream << live_bitmap << " " << *live_bitmap << "\n";
897 }
898 if (mark_bitmap != nullptr) {
899 stream << mark_bitmap << " " << *mark_bitmap << "\n";
900 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700901 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700902 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700903 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700904 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700905}
906
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800907void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700908 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
909 // Ignore early dawn of the universe verifications.
910 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.load()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800911 return;
912 }
913 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
914 mirror::Object::ClassOffset().Int32Value();
915 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
916 if (UNLIKELY(c == NULL)) {
917 LOG(FATAL) << "Null class in object: " << obj;
918 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
919 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
920 }
921 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
922 // Note: we don't use the accessors here as they have internal sanity checks
923 // that we don't want to run
924 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
925 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
926 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
927 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
928 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700929
Mathieu Chartier590fee92013-09-13 13:46:47 -0700930 if (verify_object_mode_ > kVerifyAllFast) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800931 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
932 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700933 if (!IsLiveObjectLocked(obj)) {
934 DumpSpaces();
935 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700936 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700937 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700938 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
939 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700940 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700941}
942
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800943void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700944 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700945 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700946}
947
948void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700949 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700950 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700951}
952
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700953inline size_t Heap::RecordAllocationInstrumented(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700954 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700955 DCHECK_GT(size, 0u);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700956 size_t old_num_bytes_allocated = static_cast<size_t>(num_bytes_allocated_.fetch_add(size));
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700957
958 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700959 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700960 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700961 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700962
963 // TODO: Update these atomically.
964 RuntimeStats* global_stats = Runtime::Current()->GetStats();
965 ++global_stats->allocated_objects;
966 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700967 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700968
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700969 // This is safe to do since the GC will never free objects which are neither in the allocation
970 // stack or the live bitmap.
971 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700972 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700973 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700974
975 return old_num_bytes_allocated + size;
Carl Shapiro58551df2011-07-24 03:09:51 -0700976}
977
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700978void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700979 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700980 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700981
982 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700983 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700984 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700985 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700986
987 // TODO: Do this concurrently.
988 RuntimeStats* global_stats = Runtime::Current()->GetStats();
989 global_stats->freed_objects += freed_objects;
990 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700991 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700992}
993
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700994inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::AllocSpace* space, size_t alloc_size,
995 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700996 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700997 return NULL;
998 }
999 return space->Alloc(self, alloc_size, bytes_allocated);
1000}
1001
1002// DlMallocSpace-specific version.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001003inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
1004 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -07001005 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001006 return nullptr;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001007 }
Mathieu Chartier720ef762013-08-17 14:46:54 -07001008 if (LIKELY(!running_on_valgrind_)) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001009 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
1010 } else {
1011 return space->Alloc(self, alloc_size, bytes_allocated);
1012 }
1013}
1014
1015template <class T>
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001016inline mirror::Object* Heap::AllocateInstrumented(Thread* self, T* space, size_t alloc_size,
1017 size_t* bytes_allocated) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001018 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
1019 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -07001020 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001021 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -07001022
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001023 mirror::Object* ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
1024 if (LIKELY(ptr != NULL)) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001025 return ptr;
1026 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001027 return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
1028}
1029
Mathieu Chartier720ef762013-08-17 14:46:54 -07001030mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space,
1031 size_t alloc_size, size_t* bytes_allocated) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -07001032 mirror::Object* ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001033
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001034 // The allocation failed. If the GC is running, block until it completes, and then retry the
1035 // allocation.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001036 collector::GcType last_gc = WaitForGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001037 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001038 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001039 ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001040 if (ptr != NULL) {
1041 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001042 }
1043 }
1044
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001045 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -07001046 for (size_t i = static_cast<size_t>(last_gc) + 1;
1047 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001048 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -07001049 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001050 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001051 case collector::kGcTypeSticky: {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001052 const size_t alloc_space_size = non_moving_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001053 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
Mathieu Chartier590fee92013-09-13 13:46:47 -07001054 non_moving_space_->Capacity() - alloc_space_size >=
1055 min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001056 break;
1057 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001058 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001059 run_gc = have_zygote_space_;
1060 break;
Ian Rogers1d54e732013-05-02 21:10:01 -07001061 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001062 run_gc = true;
1063 break;
1064 default:
Mathieu Chartier590fee92013-09-13 13:46:47 -07001065 LOG(FATAL) << "Invalid GC type";
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001066 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001067
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001068 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001069 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -07001070 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001071 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001072 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001073
1074 // Did we free sufficient memory for the allocation to succeed?
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001075 ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001076 if (ptr != NULL) {
1077 return ptr;
1078 }
1079 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001080 }
1081
1082 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001083 // Try harder, growing the heap if necessary.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001084 ptr = TryToAllocateInstrumented(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001085 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001086 return ptr;
1087 }
1088
Elliott Hughes81ff3182012-03-23 20:35:56 -07001089 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1090 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1091 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001092
Mathieu Chartier590fee92013-09-13 13:46:47 -07001093 // TODO: Run finalization, but this can cause more allocations to occur.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001094 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1095 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001096
Mathieu Chartier590fee92013-09-13 13:46:47 -07001097 // We don't need a WaitForGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -07001098 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001099 return TryToAllocateInstrumented(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001100}
1101
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001102void Heap::SetTargetHeapUtilization(float target) {
1103 DCHECK_GT(target, 0.0f); // asserted in Java code
1104 DCHECK_LT(target, 1.0f);
1105 target_utilization_ = target;
1106}
1107
Ian Rogers1d54e732013-05-02 21:10:01 -07001108size_t Heap::GetObjectsAllocated() const {
1109 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001110 for (space::AllocSpace* space : alloc_spaces_) {
1111 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001112 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001113 return total;
1114}
1115
Ian Rogers1d54e732013-05-02 21:10:01 -07001116size_t Heap::GetObjectsAllocatedEver() const {
1117 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001118 for (space::AllocSpace* space : alloc_spaces_) {
1119 total += space->GetTotalObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001120 }
1121 return total;
1122}
1123
1124size_t Heap::GetBytesAllocatedEver() const {
1125 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001126 for (space::AllocSpace* space : alloc_spaces_) {
1127 total += space->GetTotalBytesAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001128 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001129 return total;
1130}
1131
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001132class InstanceCounter {
1133 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001134 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001135 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001136 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001137 }
1138
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001139 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001140 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001141 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001142 if (use_is_assignable_from_) {
1143 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
1144 ++counts_[i];
1145 }
1146 } else {
1147 if (instance_class == classes_[i]) {
1148 ++counts_[i];
1149 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001150 }
1151 }
1152 }
1153
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001154 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001155 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001156 bool use_is_assignable_from_;
1157 uint64_t* const counts_;
1158
1159 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001160};
1161
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001162void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001163 uint64_t* counts) {
1164 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1165 // is empty, so the live bitmap is the only place we need to look.
1166 Thread* self = Thread::Current();
1167 self->TransitionFromRunnableToSuspended(kNative);
1168 CollectGarbage(false);
1169 self->TransitionFromSuspendedToRunnable();
1170
1171 InstanceCounter counter(classes, use_is_assignable_from, counts);
1172 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001173 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001174}
1175
Elliott Hughes3b78c942013-01-15 17:35:41 -08001176class InstanceCollector {
1177 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001178 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001179 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1180 : class_(c), max_count_(max_count), instances_(instances) {
1181 }
1182
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001183 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1184 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001185 if (instance_class == class_) {
1186 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001187 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001188 }
1189 }
1190 }
1191
1192 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001193 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001194 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001195 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001196
1197 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1198};
1199
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001200void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1201 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001202 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1203 // is empty, so the live bitmap is the only place we need to look.
1204 Thread* self = Thread::Current();
1205 self->TransitionFromRunnableToSuspended(kNative);
1206 CollectGarbage(false);
1207 self->TransitionFromSuspendedToRunnable();
1208
1209 InstanceCollector collector(c, max_count, instances);
1210 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1211 GetLiveBitmap()->Visit(collector);
1212}
1213
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001214class ReferringObjectsFinder {
1215 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001216 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1217 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001218 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1219 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1220 }
1221
1222 // For bitmap Visit.
1223 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1224 // annotalysis on visitors.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001225 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
1226 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(o), *this, true);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001227 }
1228
1229 // For MarkSweep::VisitObjectReferences.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001230 void operator()(mirror::Object* referrer, mirror::Object* object,
Brian Carlstromdf629502013-07-17 22:39:56 -07001231 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001232 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001233 referring_objects_.push_back(referrer);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001234 }
1235 }
1236
1237 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001238 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001239 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001240 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001241
1242 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1243};
1244
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001245void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1246 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001247 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1248 // is empty, so the live bitmap is the only place we need to look.
1249 Thread* self = Thread::Current();
1250 self->TransitionFromRunnableToSuspended(kNative);
1251 CollectGarbage(false);
1252 self->TransitionFromSuspendedToRunnable();
1253
1254 ReferringObjectsFinder finder(o, max_count, referring_objects);
1255 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1256 GetLiveBitmap()->Visit(finder);
1257}
1258
Ian Rogers30fab402012-01-23 15:43:46 -08001259void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001260 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1261 // last GC will not have necessarily been cleared.
Ian Rogers1d54e732013-05-02 21:10:01 -07001262 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001263}
1264
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001265void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001266 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -07001267 Thread* self = Thread::Current();
1268 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001269 // Try to see if we have any Zygote spaces.
1270 if (have_zygote_space_) {
1271 return;
1272 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001273 VLOG(heap) << "Starting PreZygoteFork";
1274 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1275 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
1276 // Trim the pages at the end of the non moving space.
1277 non_moving_space_->Trim();
1278 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1279 // Create a new bump pointer space which we will compact into.
1280 if (semi_space_collector_ != nullptr) {
1281 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1282 non_moving_space_->Limit());
1283 // Compact the bump pointer space to a new zygote bump pointer space.
1284 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1285 Compact(&target_space, bump_pointer_space_);
1286 CHECK_EQ(temp_space_->GetBytesAllocated(), 0U);
1287 total_objects_freed_ever_ += semi_space_collector_->GetFreedObjects();
1288 total_bytes_freed_ever_ += semi_space_collector_->GetFreedBytes();
1289 // Update the end and write out image.
1290 non_moving_space_->SetEnd(target_space.End());
1291 non_moving_space_->SetLimit(target_space.Limit());
1292 accounting::SpaceBitmap* bitmap = non_moving_space_->GetLiveBitmap();
1293 // Record the allocations in the bitmap.
1294 VLOG(heap) << "Recording zygote allocations";
1295 mirror::Object* obj = reinterpret_cast<mirror::Object*>(target_space.Begin());
1296 const mirror::Object* end = reinterpret_cast<const mirror::Object*>(target_space.End());
1297 while (obj < end) {
1298 bitmap->Set(obj);
1299 obj = space::BumpPointerSpace::GetNextObject(obj);
1300 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001301 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001302 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
1303 // the remaining available heap memory.
1304 space::DlMallocSpace* zygote_space = non_moving_space_;
1305 non_moving_space_ = zygote_space->CreateZygoteSpace("alloc space");
1306 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -07001307 // Change the GC retention policy of the zygote space to only collect when full.
1308 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001309 AddSpace(non_moving_space_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001310 have_zygote_space_ = true;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001311 zygote_space->InvalidateMSpace();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001312 // Create the zygote space mod union table.
1313 accounting::ModUnionTable* mod_union_table =
1314 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1315 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1316 AddModUnionTable(mod_union_table);
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001317 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001318 for (const auto& collector : garbage_collectors_) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001319 collector->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001320 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001321}
1322
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001323void Heap::FlushAllocStack() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001324 MarkAllocStack(non_moving_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001325 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001326 allocation_stack_->Reset();
1327}
1328
Ian Rogers1d54e732013-05-02 21:10:01 -07001329void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1330 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001331 mirror::Object** limit = stack->End();
1332 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1333 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001334 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001335 if (LIKELY(bitmap->HasAddress(obj))) {
1336 bitmap->Set(obj);
1337 } else {
1338 large_objects->Set(obj);
1339 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001340 }
1341}
1342
Mathieu Chartier590fee92013-09-13 13:46:47 -07001343const char* PrettyCause(GcCause cause) {
1344 switch (cause) {
1345 case kGcCauseForAlloc: return "Alloc";
1346 case kGcCauseBackground: return "Background";
1347 case kGcCauseExplicit: return "Explicit";
1348 default:
1349 LOG(FATAL) << "Unreachable";
1350 }
1351 return "";
1352}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001353
Mathieu Chartier590fee92013-09-13 13:46:47 -07001354void Heap::SwapSemiSpaces() {
1355 // Swap the spaces so we allocate into the space which we just evacuated.
1356 std::swap(bump_pointer_space_, temp_space_);
1357}
1358
1359void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
1360 space::ContinuousMemMapAllocSpace* source_space) {
1361 CHECK(kMovingCollector);
1362 CHECK_NE(target_space, source_space) << "In-place compaction unsupported";
1363 if (target_space != source_space) {
1364 semi_space_collector_->SetFromSpace(source_space);
1365 semi_space_collector_->SetToSpace(target_space);
1366 semi_space_collector_->Run(false);
1367 }
1368}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001369
Ian Rogers1d54e732013-05-02 21:10:01 -07001370collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1371 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001372 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001373 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001374 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001375 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001376 if (self->IsHandlingStackOverflow()) {
1377 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1378 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001379 {
1380 gc_complete_lock_->AssertNotHeld(self);
1381 MutexLock mu(self, *gc_complete_lock_);
1382 // Ensure there is only one GC at a time.
1383 WaitForGcToCompleteLocked(self);
1384 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1385 // Not doing at the moment to ensure soft references are cleared.
1386 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
1387 if (gc_disable_count_ != 0) {
1388 LOG(WARNING) << "Skipping GC due to disable count " << gc_disable_count_;
1389 return collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001390 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001391 is_gc_running_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001392 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001393
Mathieu Chartier590fee92013-09-13 13:46:47 -07001394 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
1395 ++runtime->GetStats()->gc_for_alloc_count;
1396 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001397 }
1398
Ian Rogers1d54e732013-05-02 21:10:01 -07001399 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001400 uint64_t gc_start_size = GetBytesAllocated();
1401 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001402 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001403 // Back to back GCs can cause 0 ms of wait time in between GC invocations.
1404 if (LIKELY(ms_delta != 0)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001405 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001406 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1407 }
1408
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001409 if (gc_type == collector::kGcTypeSticky &&
Mathieu Chartier590fee92013-09-13 13:46:47 -07001410 non_moving_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001411 gc_type = collector::kGcTypePartial;
1412 }
1413
Ian Rogers1d54e732013-05-02 21:10:01 -07001414 DCHECK_LT(gc_type, collector::kGcTypeMax);
1415 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001416
Mathieu Chartier590fee92013-09-13 13:46:47 -07001417 collector::GarbageCollector* collector = nullptr;
1418 if (kMovingCollector) {
1419 gc_type = semi_space_collector_->GetGcType();
1420 CHECK_EQ(temp_space_->GetObjectsAllocated(), 0U);
1421 semi_space_collector_->SetFromSpace(bump_pointer_space_);
1422 semi_space_collector_->SetToSpace(temp_space_);
1423 mprotect(temp_space_->Begin(), temp_space_->Capacity(), PROT_READ | PROT_WRITE);
1424 }
1425 for (const auto& cur_collector : garbage_collectors_) {
1426 if (cur_collector->IsConcurrent() == concurrent_gc_ &&
1427 cur_collector->GetGcType() == gc_type) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001428 collector = cur_collector;
1429 break;
1430 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001431 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001432 if (kMovingCollector) {
1433 gc_type = collector::kGcTypeFull;
1434 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001435 CHECK(collector != NULL)
1436 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1437 << " and type=" << gc_type;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001438
Mathieu Chartier590fee92013-09-13 13:46:47 -07001439 ATRACE_BEGIN(StringPrintf("%s %s GC", PrettyCause(gc_cause), collector->GetName()).c_str());
1440
1441 collector->Run(clear_soft_references);
Ian Rogers1d54e732013-05-02 21:10:01 -07001442 total_objects_freed_ever_ += collector->GetFreedObjects();
1443 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001444
1445 // Grow the heap so that we know when to perform the next GC.
1446 GrowForUtilization(gc_type, collector->GetDurationNs());
1447
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001448 if (care_about_pause_times_) {
1449 const size_t duration = collector->GetDurationNs();
1450 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1451 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001452 bool was_slow = duration > long_gc_log_threshold_ ||
1453 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001454 if (!was_slow) {
1455 for (uint64_t pause : pauses) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001456 was_slow = was_slow || pause > long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001457 }
1458 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001459 if (was_slow) {
1460 const size_t percent_free = GetPercentFree();
1461 const size_t current_heap_size = GetBytesAllocated();
1462 const size_t total_memory = GetTotalMemory();
1463 std::ostringstream pause_string;
1464 for (size_t i = 0; i < pauses.size(); ++i) {
1465 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1466 << ((i != pauses.size() - 1) ? ", " : "");
1467 }
1468 LOG(INFO) << gc_cause << " " << collector->GetName()
1469 << " GC freed " << collector->GetFreedObjects() << "("
1470 << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1471 << collector->GetFreedLargeObjects() << "("
1472 << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1473 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1474 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1475 << " total " << PrettyDuration((duration / 1000) * 1000);
1476 if (VLOG_IS_ON(heap)) {
1477 LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
1478 }
1479 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001480 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001481
Ian Rogers15bf2d32012-08-28 17:33:04 -07001482 {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001483 MutexLock mu(self, *gc_complete_lock_);
1484 is_gc_running_ = false;
1485 last_gc_type_ = gc_type;
1486 // Wake anyone who may have been waiting for the GC to complete.
1487 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001488 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001489
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001490 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001491
1492 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001493 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001494 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001495}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001496
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001497static mirror::Object* RootMatchesObjectVisitor(mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001498 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001499 if (root == obj) {
1500 LOG(INFO) << "Object " << obj << " is a root";
1501 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001502 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001503}
1504
1505class ScanVisitor {
1506 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001507 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001508 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001509 }
1510};
1511
Ian Rogers1d54e732013-05-02 21:10:01 -07001512// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001513class VerifyReferenceVisitor {
1514 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001515 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001516 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001517 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001518
1519 bool Failed() const {
1520 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001521 }
1522
1523 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001524 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001525 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1526 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001527 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001528 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001529 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1530 accounting::CardTable* card_table = heap_->GetCardTable();
1531 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1532 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001533 if (!failed_) {
1534 // Print message on only on first failure to prevent spam.
1535 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
1536 failed_ = true;
1537 }
1538 if (obj != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001539 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001540 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
1541 << offset << "\n card value = " << static_cast<int>(*card_addr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001542 if (heap_->IsValidObjectAddress(obj->GetClass())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001543 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1544 } else {
1545 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
1546 }
1547
1548 // Attmept to find the class inside of the recently freed objects.
1549 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001550 if (ref_space != nullptr && ref_space->IsDlMallocSpace()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001551 space::DlMallocSpace* space = ref_space->AsDlMallocSpace();
1552 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
1553 if (ref_class != nullptr) {
1554 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
1555 << PrettyClass(ref_class);
1556 } else {
1557 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
1558 }
1559 }
1560
Mathieu Chartier590fee92013-09-13 13:46:47 -07001561 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001562 ref->GetClass()->IsClass()) {
1563 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1564 } else {
1565 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
1566 << ") is not a valid heap address";
1567 }
1568
Ian Rogers1d54e732013-05-02 21:10:01 -07001569 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1570 void* cover_begin = card_table->AddrFromCard(card_addr);
1571 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1572 accounting::CardTable::kCardSize);
1573 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1574 << "-" << cover_end;
1575 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001576
Ian Rogers1d54e732013-05-02 21:10:01 -07001577 // Print out how the object is live.
1578 if (bitmap != NULL && bitmap->Test(obj)) {
1579 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1580 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001581 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001582 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1583 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001584 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001585 LOG(ERROR) << "Object " << obj << " found in live stack";
1586 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001587 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1588 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
1589 }
1590 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1591 LOG(ERROR) << "Ref " << ref << " found in live stack";
1592 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001593 // Attempt to see if the card table missed the reference.
1594 ScanVisitor scan_visitor;
1595 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1596 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001597 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001598
1599 // Search to see if any of the roots reference our object.
1600 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1601 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1602
1603 // Search to see if any of the roots reference our reference.
1604 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1605 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1606 } else {
1607 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001608 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001609 }
1610 }
1611
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001612 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001613 return heap_->IsLiveObjectLocked(obj, true, false, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001614 }
1615
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001616 static mirror::Object* VerifyRoots(mirror::Object* root, void* arg) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001617 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001618 (*visitor)(nullptr, root, MemberOffset(0), true);
1619 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001620 }
1621
1622 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001623 Heap* const heap_;
1624 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001625};
1626
Ian Rogers1d54e732013-05-02 21:10:01 -07001627// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001628class VerifyObjectVisitor {
1629 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001630 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001631
Mathieu Chartier590fee92013-09-13 13:46:47 -07001632 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001633 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001634 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1635 // be live or else how did we find it in the live bitmap?
1636 VerifyReferenceVisitor visitor(heap_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001637 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001638 collector::MarkSweep::VisitObjectReferences(obj, visitor, true);
1639 if (obj->GetClass()->IsReferenceClass()) {
1640 visitor(obj, heap_->GetReferenceReferent(obj), MemberOffset(0), false);
1641 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001642 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001643 }
1644
Mathieu Chartier590fee92013-09-13 13:46:47 -07001645 static void VisitCallback(mirror::Object* obj, void* arg)
1646 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1647 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
1648 visitor->operator()(obj);
1649 }
1650
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001651 bool Failed() const {
1652 return failed_;
1653 }
1654
1655 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001656 Heap* const heap_;
1657 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001658};
1659
1660// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001661bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001662 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001663 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001664 allocation_stack_->Sort();
1665 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001666 VerifyObjectVisitor visitor(this);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001667 // Verify objects in the allocation stack since these will be objects which were:
1668 // 1. Allocated prior to the GC (pre GC verification).
1669 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001670 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001671 // pointing to dead objects if they are not reachable.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001672 VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
1673 // Verify the roots:
1674 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001675 if (visitor.Failed()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001676 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001677 for (const auto& table_pair : mod_union_tables_) {
1678 accounting::ModUnionTable* mod_union_table = table_pair.second;
1679 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
1680 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001681 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001682 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001683 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001684 return true;
1685}
1686
1687class VerifyReferenceCardVisitor {
1688 public:
1689 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1690 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1691 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001692 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001693 }
1694
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001695 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1696 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001697 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1698 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001699 // Filter out class references since changing an object's class does not mark the card as dirty.
1700 // Also handles large objects, since the only reference they hold is a class reference.
1701 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001702 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001703 // If the object is not dirty and it is referencing something in the live stack other than
1704 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001705 if (!card_table->AddrIsInCardTable(obj)) {
1706 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1707 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001708 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001709 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1710 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001711 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001712 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1713 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001714 LOG(ERROR) << "Object " << obj << " found in live stack";
1715 }
1716 if (heap_->GetLiveBitmap()->Test(obj)) {
1717 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1718 }
1719 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1720 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1721
1722 // Print which field of the object is dead.
1723 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001724 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001725 CHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001726 const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
1727 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001728 CHECK(fields != NULL);
1729 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001730 const mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001731 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1732 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1733 << PrettyField(cur);
1734 break;
1735 }
1736 }
1737 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001738 const mirror::ObjectArray<mirror::Object>* object_array =
1739 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001740 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1741 if (object_array->Get(i) == ref) {
1742 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1743 }
1744 }
1745 }
1746
1747 *failed_ = true;
1748 }
1749 }
1750 }
1751 }
1752
1753 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001754 Heap* const heap_;
1755 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001756};
1757
1758class VerifyLiveStackReferences {
1759 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001760 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001761 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001762 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001763
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001764 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001765 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1766 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001767 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(obj), visitor, true);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001768 }
1769
1770 bool Failed() const {
1771 return failed_;
1772 }
1773
1774 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001775 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001776 bool failed_;
1777};
1778
1779bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001780 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001781
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001782 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001783 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001784 VerifyLiveStackReferences visitor(this);
1785 GetLiveBitmap()->Visit(visitor);
1786
1787 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001788 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001789 visitor(*it);
1790 }
1791
1792 if (visitor.Failed()) {
1793 DumpSpaces();
1794 return false;
1795 }
1796 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001797}
1798
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001799void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001800 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001801}
1802
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001803accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
1804 auto it = mod_union_tables_.find(space);
1805 if (it == mod_union_tables_.end()) {
1806 return nullptr;
1807 }
1808 return it->second;
1809}
1810
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001811void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001812 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001813 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001814 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
1815 if (table != nullptr) {
1816 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
1817 "ImageModUnionClearCards";
1818 base::TimingLogger::ScopedSplit split(name, &timings);
1819 table->ClearCards();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001820 } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001821 base::TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001822 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1823 // were dirty before the GC started.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001824 // TODO: Don't need to use atomic.
1825 // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
1826 // roots and then we scan / update mod union tables after. We will always scan either card.//
1827 // If we end up with the non aged card, we scan it it in the pause.
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001828 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001829 }
1830 }
1831}
1832
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001833static mirror::Object* IdentityCallback(mirror::Object* obj, void*) {
1834 return obj;
1835}
1836
Ian Rogers1d54e732013-05-02 21:10:01 -07001837void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001838 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1839 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001840
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001841 if (verify_pre_gc_heap_) {
1842 thread_list->SuspendAll();
1843 {
1844 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1845 if (!VerifyHeapReferences()) {
1846 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1847 }
1848 }
1849 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001850 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001851
1852 // Check that all objects which reference things in the live stack are on dirty cards.
1853 if (verify_missing_card_marks_) {
1854 thread_list->SuspendAll();
1855 {
1856 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1857 SwapStacks();
1858 // Sort the live stack so that we can quickly binary search it later.
1859 if (!VerifyMissingCardMarks()) {
1860 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1861 }
1862 SwapStacks();
1863 }
1864 thread_list->ResumeAll();
1865 }
1866
1867 if (verify_mod_union_table_) {
1868 thread_list->SuspendAll();
1869 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001870 for (const auto& table_pair : mod_union_tables_) {
1871 accounting::ModUnionTable* mod_union_table = table_pair.second;
1872 mod_union_table->UpdateAndMarkReferences(IdentityCallback, nullptr);
1873 mod_union_table->Verify();
1874 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001875 thread_list->ResumeAll();
1876 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001877}
1878
Ian Rogers1d54e732013-05-02 21:10:01 -07001879void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001880 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1881 // reachable objects.
1882 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001883 Thread* self = Thread::Current();
1884 CHECK_NE(self->GetState(), kRunnable);
Ian Rogers1d54e732013-05-02 21:10:01 -07001885 {
1886 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1887 // Swapping bound bitmaps does nothing.
1888 gc->SwapBitmaps();
1889 if (!VerifyHeapReferences()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001890 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
Ian Rogers1d54e732013-05-02 21:10:01 -07001891 }
1892 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001893 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001894 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001895}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001896
Ian Rogers1d54e732013-05-02 21:10:01 -07001897void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001898 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001899 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001900 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001901 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001902 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001903 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001904}
1905
Mathieu Chartier590fee92013-09-13 13:46:47 -07001906collector::GcType Heap::WaitForGcToComplete(Thread* self) {
1907 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1908 MutexLock mu(self, *gc_complete_lock_);
1909 return WaitForGcToCompleteLocked(self);
1910}
1911
1912collector::GcType Heap::WaitForGcToCompleteLocked(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001913 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001914 uint64_t wait_start = NanoTime();
1915 while (is_gc_running_) {
1916 ATRACE_BEGIN("GC: Wait For Completion");
1917 // We must wait, change thread state then sleep on gc_complete_cond_;
1918 gc_complete_cond_->Wait(self);
1919 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001920 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001921 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001922 uint64_t wait_time = NanoTime() - wait_start;
1923 total_wait_time_ += wait_time;
1924 if (wait_time > long_pause_log_threshold_) {
1925 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time);
1926 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001927 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001928}
1929
Elliott Hughesc967f782012-04-16 10:23:15 -07001930void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001931 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001932 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001933 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001934}
1935
1936size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001937 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001938}
1939
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001940void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001941 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001942 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001943 << PrettySize(GetMaxMemory());
1944 max_allowed_footprint = GetMaxMemory();
1945 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001946 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001947}
1948
Mathieu Chartier590fee92013-09-13 13:46:47 -07001949bool Heap::IsMovableObject(const mirror::Object* obj) const {
1950 if (kMovingCollector) {
1951 DCHECK(!IsInTempSpace(obj));
1952 if (bump_pointer_space_->HasAddress(obj)) {
1953 return true;
1954 }
1955 }
1956 return false;
1957}
1958
1959bool Heap::IsInTempSpace(const mirror::Object* obj) const {
1960 if (temp_space_->HasAddress(obj) && !temp_space_->Contains(obj)) {
1961 return true;
1962 }
1963 return false;
1964}
1965
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001966void Heap::UpdateMaxNativeFootprint() {
1967 size_t native_size = native_bytes_allocated_;
1968 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1969 size_t target_size = native_size / GetTargetHeapUtilization();
1970 if (target_size > native_size + max_free_) {
1971 target_size = native_size + max_free_;
1972 } else if (target_size < native_size + min_free_) {
1973 target_size = native_size + min_free_;
1974 }
1975 native_footprint_gc_watermark_ = target_size;
1976 native_footprint_limit_ = 2 * target_size - native_size;
1977}
1978
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001979void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001980 // We know what our utilization is at this moment.
1981 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001982 const size_t bytes_allocated = GetBytesAllocated();
1983 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001984 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001985
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001986 size_t target_size;
1987 if (gc_type != collector::kGcTypeSticky) {
1988 // Grow the heap for non sticky GC.
1989 target_size = bytes_allocated / GetTargetHeapUtilization();
1990 if (target_size > bytes_allocated + max_free_) {
1991 target_size = bytes_allocated + max_free_;
1992 } else if (target_size < bytes_allocated + min_free_) {
1993 target_size = bytes_allocated + min_free_;
1994 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001995 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001996 next_gc_type_ = collector::kGcTypeSticky;
1997 } else {
1998 // Based on how close the current heap size is to the target size, decide
1999 // whether or not to do a partial or sticky GC next.
2000 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
2001 next_gc_type_ = collector::kGcTypeSticky;
2002 } else {
2003 next_gc_type_ = collector::kGcTypePartial;
2004 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002005
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002006 // If we have freed enough memory, shrink the heap back down.
2007 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
2008 target_size = bytes_allocated + max_free_;
2009 } else {
2010 target_size = std::max(bytes_allocated, max_allowed_footprint_);
2011 }
2012 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002013
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002014 if (!ignore_max_footprint_) {
2015 SetIdealFootprint(target_size);
2016
2017 if (concurrent_gc_) {
2018 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002019 // Calculate the estimated GC duration.
2020 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
2021 // Estimate how many remaining bytes we will have when we need to start the next GC.
2022 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
2023 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
2024 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
2025 // A never going to happen situation that from the estimated allocation rate we will exceed
2026 // the applications entire footprint with the given estimated allocation rate. Schedule
2027 // another GC straight away.
2028 concurrent_start_bytes_ = bytes_allocated;
2029 } else {
2030 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
2031 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
2032 // right away.
2033 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
2034 }
2035 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
2036 DCHECK_LE(max_allowed_footprint_, growth_limit_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08002037 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002038 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07002039}
2040
jeffhaoc1160702011-10-27 15:48:45 -07002041void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08002042 growth_limit_ = capacity_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002043 non_moving_space_->ClearGrowthLimit();
jeffhaoc1160702011-10-27 15:48:45 -07002044}
2045
Elliott Hughesadb460d2011-10-05 17:02:34 -07002046void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002047 MemberOffset reference_queue_offset,
2048 MemberOffset reference_queueNext_offset,
2049 MemberOffset reference_pendingNext_offset,
2050 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002051 reference_referent_offset_ = reference_referent_offset;
2052 reference_queue_offset_ = reference_queue_offset;
2053 reference_queueNext_offset_ = reference_queueNext_offset;
2054 reference_pendingNext_offset_ = reference_pendingNext_offset;
2055 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
2056 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
2057 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
2058 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
2059 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
2060 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
2061}
2062
Mathieu Chartier590fee92013-09-13 13:46:47 -07002063void Heap::SetReferenceReferent(mirror::Object* reference, mirror::Object* referent) {
2064 DCHECK(reference != NULL);
2065 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
2066 reference->SetFieldObject(reference_referent_offset_, referent, true);
2067}
2068
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002069mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002070 DCHECK(reference != NULL);
2071 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002072 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002073}
2074
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002075void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002076 DCHECK(reference != NULL);
2077 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002078 reference->SetFieldObject(reference_referent_offset_, nullptr, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002079}
2080
2081// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002082bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002083 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002084 const mirror::Object* queue =
2085 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
2086 const mirror::Object* queue_next =
2087 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002088 return (queue != NULL) && (queue_next == NULL);
2089}
2090
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002091void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002092 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002093 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
2094 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002095 EnqueuePendingReference(ref, cleared_reference_list);
2096}
2097
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07002098bool Heap::IsEnqueued(mirror::Object* ref) {
2099 // Since the references are stored as cyclic lists it means that once enqueued, the pending next
2100 // will always be non-null.
2101 return ref->GetFieldObject<mirror::Object*>(GetReferencePendingNextOffset(), false) != nullptr;
2102}
2103
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002104void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002105 DCHECK(ref != NULL);
2106 DCHECK(list != NULL);
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07002107 if (*list == NULL) {
2108 // 1 element cyclic queue, ie: Reference ref = ..; ref.pendingNext = ref;
2109 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
2110 *list = ref;
2111 } else {
2112 mirror::Object* head =
2113 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
2114 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
2115 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002116 }
2117}
2118
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002119mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002120 DCHECK(list != NULL);
2121 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002122 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
2123 false);
2124 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07002125
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002126 // Note: the following code is thread-safe because it is only called from ProcessReferences which
2127 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07002128 if (*list == head) {
2129 ref = *list;
2130 *list = NULL;
2131 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002132 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
2133 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002134 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
2135 ref = head;
2136 }
2137 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
2138 return ref;
2139}
2140
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002141void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002142 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08002143 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08002144 ArgArray arg_array(NULL, 0);
2145 arg_array.Append(reinterpret_cast<uint32_t>(object));
2146 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07002147 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002148}
2149
Mathieu Chartier590fee92013-09-13 13:46:47 -07002150void Heap::PrintReferenceQueue(std::ostream& os, mirror::Object** queue) {
2151 os << "Refernece queue " << queue << "\n";
2152 if (queue != nullptr) {
2153 mirror::Object* list = *queue;
2154 if (list != nullptr) {
2155 mirror::Object* cur = list;
2156 do {
2157 mirror::Object* pending_next =
2158 cur->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
2159 os << "PendingNext=" << pending_next;
2160 if (cur->GetClass()->IsFinalizerReferenceClass()) {
2161 os << " Zombie=" <<
2162 cur->GetFieldObject<mirror::Object*>(finalizer_reference_zombie_offset_, false);
2163 }
2164 os << "\n";
2165 cur = pending_next;
2166 } while (cur != list);
2167 }
2168 }
2169}
2170
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002171void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002172 DCHECK(cleared != nullptr);
2173 mirror::Object* list = *cleared;
2174 if (list != nullptr) {
Ian Rogers64b6d142012-10-29 16:34:15 -07002175 // When a runtime isn't started there are no reference queues to care about so ignore.
2176 if (LIKELY(Runtime::Current()->IsStarted())) {
2177 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08002178 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08002179 ArgArray arg_array(NULL, 0);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002180 arg_array.Append(reinterpret_cast<uint32_t>(list));
Jeff Hao5d917302013-02-27 17:57:33 -08002181 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07002182 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07002183 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002184 *cleared = nullptr;
Elliott Hughesadb460d2011-10-05 17:02:34 -07002185 }
2186}
2187
Ian Rogers1f539342012-10-03 21:09:42 -07002188void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07002189 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07002190 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08002191 DCHECK(concurrent_gc_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002192 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
2193 self->IsHandlingStackOverflow()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002194 return;
2195 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002196 // We already have a request pending, no reason to start more until we update
2197 // concurrent_start_bytes_.
2198 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers120f1c72012-09-28 17:17:10 -07002199 JNIEnv* env = self->GetJniEnv();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002200 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2201 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002202 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2203 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002204 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002205}
2206
Ian Rogers81d425b2012-09-27 16:03:43 -07002207void Heap::ConcurrentGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002208 if (Runtime::Current()->IsShuttingDown(self)) {
2209 return;
Mathieu Chartier2542d662012-06-21 17:14:11 -07002210 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002211 // Wait for any GCs currently running to finish.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002212 if (WaitForGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002213 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002214 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002215}
2216
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002217void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08002218 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
2219 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
2220 // a space it will hold its lock and can become a cause of jank.
2221 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
2222 // forking.
2223
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002224 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2225 // because that only marks object heads, so a large array looks like lots of empty space. We
2226 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2227 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2228 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2229 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08002230 uint64_t ms_time = MilliTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002231 // Don't bother trimming the alloc space if a heap trim occurred in the last two seconds.
2232 if (ms_time - last_trim_time_ms_ < 2 * 1000) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002233 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002234 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002235
2236 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002237 Runtime* runtime = Runtime::Current();
2238 if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self)) {
2239 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2240 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2241 // as we don't hold the lock while requesting the trim).
2242 return;
Ian Rogerse1d490c2012-02-03 09:09:07 -08002243 }
Ian Rogers48931882013-01-22 14:35:16 -08002244
Ian Rogers1d54e732013-05-02 21:10:01 -07002245 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002246 ListenForProcessStateChange();
2247
2248 // Trim only if we do not currently care about pause times.
2249 if (!care_about_pause_times_) {
2250 JNIEnv* env = self->GetJniEnv();
2251 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2252 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2253 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2254 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2255 CHECK(!env->ExceptionCheck());
2256 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002257}
2258
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002259bool Heap::IsGCRequestPending() const {
2260 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2261}
2262
Mathieu Chartier590fee92013-09-13 13:46:47 -07002263void Heap::RunFinalization(JNIEnv* env) {
2264 // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
2265 if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
2266 CHECK(WellKnownClasses::java_lang_System != nullptr);
2267 WellKnownClasses::java_lang_System_runFinalization =
2268 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2269 CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
2270 }
2271 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2272 WellKnownClasses::java_lang_System_runFinalization);
2273}
2274
Ian Rogers1eb512d2013-10-18 15:42:20 -07002275void Heap::RegisterNativeAllocation(JNIEnv* env, int bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002276 Thread* self = ThreadForEnv(env);
2277 if (native_need_to_run_finalization_) {
2278 RunFinalization(env);
2279 UpdateMaxNativeFootprint();
2280 native_need_to_run_finalization_ = false;
2281 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002282 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002283 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002284 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
2285 // The second watermark is higher than the gc watermark. If you hit this it means you are
2286 // allocating native objects faster than the GC can keep up with.
2287 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002288 if (WaitForGcToComplete(self) != collector::kGcTypeNone) {
2289 // Just finished a GC, attempt to run finalizers.
2290 RunFinalization(env);
2291 CHECK(!env->ExceptionCheck());
2292 }
2293 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2294 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2295 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
2296 RunFinalization(env);
2297 native_need_to_run_finalization_ = false;
2298 CHECK(!env->ExceptionCheck());
2299 }
2300 // We have just run finalizers, update the native watermark since it is very likely that
2301 // finalizers released native managed allocations.
2302 UpdateMaxNativeFootprint();
2303 } else if (!IsGCRequestPending()) {
2304 if (concurrent_gc_) {
2305 RequestConcurrentGC(self);
2306 } else {
2307 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002308 }
2309 }
2310 }
2311}
2312
Ian Rogers1eb512d2013-10-18 15:42:20 -07002313void Heap::RegisterNativeFree(JNIEnv* env, int bytes) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002314 int expected_size, new_size;
2315 do {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002316 expected_size = native_bytes_allocated_.load();
2317 new_size = expected_size - bytes;
2318 if (UNLIKELY(new_size < 0)) {
2319 ScopedObjectAccess soa(env);
2320 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
2321 StringPrintf("Attempted to free %d native bytes with only %d native bytes "
2322 "registered as allocated", bytes, expected_size).c_str());
2323 break;
2324 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002325 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002326}
2327
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002328int64_t Heap::GetTotalMemory() const {
2329 int64_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002330 for (const auto& space : continuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002331 // Currently don't include the image space.
2332 if (!space->IsImageSpace()) {
2333 ret += space->Size();
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002334 }
2335 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002336 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002337 if (space->IsLargeObjectSpace()) {
2338 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2339 }
2340 }
2341 return ret;
2342}
2343
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002344void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
2345 DCHECK(mod_union_table != nullptr);
2346 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
2347}
2348
Ian Rogers1d54e732013-05-02 21:10:01 -07002349} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002350} // namespace art