blob: e20c2c5f05613511a9cb338d45ac32331ae96399 [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"
33#include "gc/accounting/mod_union_table-inl.h"
34#include "gc/accounting/space_bitmap-inl.h"
35#include "gc/collector/mark_sweep-inl.h"
36#include "gc/collector/partial_mark_sweep.h"
37#include "gc/collector/sticky_mark_sweep.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070038#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/space/image_space.h"
40#include "gc/space/large_object_space.h"
41#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070042#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080043#include "invoke_arg_array_builder.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070044#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/object.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080049#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080050#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070051#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070052#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070053#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070054#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070055#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070056#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070057
58namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070059namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070060
Mathieu Chartier720ef762013-08-17 14:46:54 -070061static constexpr bool kGCALotMode = false;
62static constexpr size_t kGcAlotInterval = KB;
63static constexpr bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070064// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070065static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070066// If true, measure the total allocation time.
Mathieu Chartier720ef762013-08-17 14:46:54 -070067static constexpr bool kMeasureAllocationTime = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070068
Mathieu Chartier0051be62012-10-12 17:47:11 -070069Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070070 double target_utilization, size_t capacity, const std::string& original_image_file_name,
Mathieu Chartier2775ee42013-08-20 17:43:47 -070071 bool concurrent_gc, size_t parallel_gc_threads, size_t conc_gc_threads,
72 bool low_memory_mode, size_t long_pause_log_threshold, size_t long_gc_log_threshold,
73 bool ignore_max_footprint)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070074 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080075 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070076 concurrent_gc_(concurrent_gc),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070077 parallel_gc_threads_(parallel_gc_threads),
78 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070079 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070080 long_pause_log_threshold_(long_pause_log_threshold),
81 long_gc_log_threshold_(long_gc_log_threshold),
82 ignore_max_footprint_(ignore_max_footprint),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070083 have_zygote_space_(false),
Mathieu Chartier94c32c52013-08-09 11:14:04 -070084 soft_ref_queue_lock_(NULL),
85 weak_ref_queue_lock_(NULL),
86 finalizer_ref_queue_lock_(NULL),
87 phantom_ref_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080088 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070089 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070090 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080091 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070092 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070093 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070094 native_footprint_gc_watermark_(initial_size),
95 native_footprint_limit_(2 * initial_size),
Mathieu Chartierc39e3422013-08-07 16:41:36 -070096 activity_thread_class_(NULL),
97 application_thread_class_(NULL),
98 activity_thread_(NULL),
99 application_thread_(NULL),
100 last_process_state_id_(NULL),
101 // Initially care about pauses in case we never get notified of process states, or if the JNI
102 // code becomes broken.
103 care_about_pause_times_(true),
Mathieu Chartier720ef762013-08-17 14:46:54 -0700104 concurrent_start_bytes_(concurrent_gc_ ? initial_size - kMinConcurrentRemainingBytes
105 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700106 total_bytes_freed_ever_(0),
107 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700108 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800109 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700110 native_bytes_allocated_(0),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700111 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700112 verify_missing_card_marks_(false),
113 verify_system_weaks_(false),
114 verify_pre_gc_heap_(false),
115 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700116 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700117 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700118 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700119 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800120 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700121 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
122 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
123 * verification is enabled, we limit the size of allocation stacks to speed up their
124 * searching.
125 */
126 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
127 : (kDesiredHeapVerification > kNoHeapVerification) ? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800128 reference_referent_offset_(0),
129 reference_queue_offset_(0),
130 reference_queueNext_offset_(0),
131 reference_pendingNext_offset_(0),
132 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700133 min_free_(min_free),
134 max_free_(max_free),
135 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700136 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700137 total_allocation_time_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700138 verify_object_mode_(kHeapVerificationNotPermitted),
139 running_on_valgrind_(RUNNING_ON_VALGRIND) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800140 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800141 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700142 }
143
Ian Rogers1d54e732013-05-02 21:10:01 -0700144 live_bitmap_.reset(new accounting::HeapBitmap(this));
145 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700146
Ian Rogers30fab402012-01-23 15:43:46 -0800147 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700148 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800149 std::string image_file_name(original_image_file_name);
150 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700151 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
152 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700153 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800154 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
155 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800156 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
157 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700158 if (oat_file_end_addr > requested_alloc_space_begin) {
159 requested_alloc_space_begin =
160 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
161 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700162 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700163 }
164
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700165 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700166 initial_size,
167 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700168 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700169 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700170 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700171 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700172
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700173 // Allocate the large object space.
174 const bool kUseFreeListSpaceForLOS = false;
175 if (kUseFreeListSpaceForLOS) {
176 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
177 } else {
178 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
179 }
180 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
181 AddDiscontinuousSpace(large_object_space_);
182
Ian Rogers1d54e732013-05-02 21:10:01 -0700183 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
184 byte* heap_begin = continuous_spaces_.front()->Begin();
185 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
186 if (continuous_spaces_.back()->IsDlMallocSpace()) {
187 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700188 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700189
Mathieu Chartier02e25112013-08-14 16:14:24 -0700190 // Mark image objects in the live bitmap.
191 for (const auto& space : continuous_spaces_) {
Ian Rogers30fab402012-01-23 15:43:46 -0800192 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700193 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700194 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800195 }
196 }
197
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800198 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700199 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700200 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700201
Mathieu Chartier161a8e02013-08-01 19:12:52 -0700202 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
Ian Rogers1d54e732013-05-02 21:10:01 -0700203 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700204
Ian Rogers1d54e732013-05-02 21:10:01 -0700205 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700206 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700207
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700208 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700209 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700210
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800211 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700212 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700213 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
214 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
215 max_allocation_stack_size_));
216 live_stack_.reset(accounting::ObjectStack::Create("live stack",
217 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700218
Mathieu Chartier65db8802012-11-20 12:36:46 -0800219 // It's still too early to take a lock because there are no threads yet, but we can create locks
220 // now. We don't create it earlier to make it clear that you can't use locks during heap
221 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700222 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700223 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
224 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700225
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700226 // Create the reference queue locks, this is required so for parallel object scanning in the GC.
227 soft_ref_queue_lock_ = new Mutex("Soft reference queue lock");
228 weak_ref_queue_lock_ = new Mutex("Weak reference queue lock");
229 finalizer_ref_queue_lock_ = new Mutex("Finalizer reference queue lock");
230 phantom_ref_queue_lock_ = new Mutex("Phantom reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700231
Ian Rogers1d54e732013-05-02 21:10:01 -0700232 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800233 last_gc_size_ = GetBytesAllocated();
234
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700235 if (ignore_max_footprint_) {
236 SetIdealFootprint(std::numeric_limits<size_t>::max());
237 concurrent_start_bytes_ = max_allowed_footprint_;
238 }
239
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800240 // Create our garbage collectors.
241 for (size_t i = 0; i < 2; ++i) {
242 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700243 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
244 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
245 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700246 }
247
Brian Carlstrom42748892013-07-18 18:04:08 -0700248 CHECK_NE(max_allowed_footprint_, 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800249 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800250 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700251 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700252}
253
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700254void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700255 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
256 if (num_threads != 0) {
257 thread_pool_.reset(new ThreadPool(num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700258 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700259}
260
261void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700262 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700263}
264
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700265static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
266 CHECK(out_value != NULL);
267 jfieldID field = env->GetStaticFieldID(clz, name, "I");
268 if (field == NULL) {
269 env->ExceptionClear();
270 return false;
271 }
272 *out_value = env->GetStaticIntField(clz, field);
273 return true;
274}
275
276void Heap::ListenForProcessStateChange() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700277 VLOG(heap) << "Heap notified of process state change";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700278
279 Thread* self = Thread::Current();
280 JNIEnvExt* env = self->GetJniEnv();
281
282 if (!have_zygote_space_) {
283 return;
284 }
285
286 if (activity_thread_class_ == NULL) {
287 jclass clz = env->FindClass("android/app/ActivityThread");
288 if (clz == NULL) {
289 env->ExceptionClear();
290 LOG(WARNING) << "Could not find activity thread class in process state change";
291 return;
292 }
293 activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
294 }
295
296 if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
297 jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
298 "currentActivityThread",
299 "()Landroid/app/ActivityThread;");
300 if (current_activity_method == NULL) {
301 env->ExceptionClear();
302 LOG(WARNING) << "Could not get method for currentActivityThread";
303 return;
304 }
305
306 jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
307 if (obj == NULL) {
308 env->ExceptionClear();
309 LOG(WARNING) << "Could not get current activity";
310 return;
311 }
312 activity_thread_ = env->NewGlobalRef(obj);
313 }
314
315 if (process_state_cares_about_pause_time_.empty()) {
316 // Just attempt to do this the first time.
317 jclass clz = env->FindClass("android/app/ActivityManager");
318 if (clz == NULL) {
319 LOG(WARNING) << "Activity manager class is null";
320 return;
321 }
322 ScopedLocalRef<jclass> activity_manager(env, clz);
323 std::vector<const char*> care_about_pauses;
324 care_about_pauses.push_back("PROCESS_STATE_TOP");
325 care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
326 // Attempt to read the constants and classify them as whether or not we care about pause times.
327 for (size_t i = 0; i < care_about_pauses.size(); ++i) {
328 int process_state = 0;
329 if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
330 process_state_cares_about_pause_time_.insert(process_state);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700331 VLOG(heap) << "Adding process state " << process_state
332 << " to set of states which care about pause time";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700333 }
334 }
335 }
336
337 if (application_thread_class_ == NULL) {
338 jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
339 if (clz == NULL) {
340 env->ExceptionClear();
341 LOG(WARNING) << "Could not get application thread class";
342 return;
343 }
344 application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
345 last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
346 if (last_process_state_id_ == NULL) {
347 env->ExceptionClear();
348 LOG(WARNING) << "Could not get last process state member";
349 return;
350 }
351 }
352
353 if (application_thread_class_ != NULL && application_thread_ == NULL) {
354 jmethodID get_application_thread =
355 env->GetMethodID(activity_thread_class_, "getApplicationThread",
356 "()Landroid/app/ActivityThread$ApplicationThread;");
357 if (get_application_thread == NULL) {
358 LOG(WARNING) << "Could not get method ID for get application thread";
359 return;
360 }
361
362 jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
363 if (obj == NULL) {
364 LOG(WARNING) << "Could not get application thread";
365 return;
366 }
367
368 application_thread_ = env->NewGlobalRef(obj);
369 }
370
371 if (application_thread_ != NULL && last_process_state_id_ != NULL) {
372 int process_state = env->GetIntField(application_thread_, last_process_state_id_);
373 env->ExceptionClear();
374
375 care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
376 process_state_cares_about_pause_time_.end();
377
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700378 VLOG(heap) << "New process state " << process_state
379 << " care about pauses " << care_about_pause_times_;
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700380 }
Mathieu Chartier82353312013-07-18 10:47:51 -0700381}
382
Ian Rogers1d54e732013-05-02 21:10:01 -0700383void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700384 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700385 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700386 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700387 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700388 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700389 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
390 continuous_spaces_.push_back(space);
391 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
392 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700393 }
394
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700395 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700396 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
397 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
398 return a->Begin() < b->Begin();
399 });
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700400
401 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
402 // avoid redundant marking.
403 bool seen_zygote = false, seen_alloc = false;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700404 for (const auto& space : continuous_spaces_) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700405 if (space->IsImageSpace()) {
406 DCHECK(!seen_zygote);
407 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700408 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700409 DCHECK(!seen_alloc);
410 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700411 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700412 seen_alloc = true;
413 }
414 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800415}
416
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700417void Heap::RegisterGCAllocation(size_t bytes) {
418 if (this != NULL) {
419 gc_memory_overhead_.fetch_add(bytes);
420 }
421}
422
423void Heap::RegisterGCDeAllocation(size_t bytes) {
424 if (this != NULL) {
425 gc_memory_overhead_.fetch_sub(bytes);
426 }
427}
428
Ian Rogers1d54e732013-05-02 21:10:01 -0700429void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
430 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
431 DCHECK(space != NULL);
432 DCHECK(space->GetLiveObjects() != NULL);
433 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
434 DCHECK(space->GetMarkObjects() != NULL);
435 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
436 discontinuous_spaces_.push_back(space);
437}
438
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700439void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700440 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700441 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700442 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800443
444 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800445 uint64_t total_paused_time = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700446 for (const auto& collector : mark_sweep_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800447 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800448 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700449 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800450 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700451 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800452 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
453 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
454 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700455 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
456 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
457 << collector->GetName() << " freed: " << freed_objects
458 << " objects with total size " << PrettySize(freed_bytes) << "\n"
459 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
460 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800461 total_duration += total_ns;
462 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700463 }
464 }
465 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700466 size_t total_objects_allocated = GetObjectsAllocatedEver();
467 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700468 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700469 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700470 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
471 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700472 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700473 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700474 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700475 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700476 os << "Total number of allocations: " << total_objects_allocated << "\n";
477 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700478 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700479 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
480 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
481 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700482 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700483 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
484 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700485 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700486}
487
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800488Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700489 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700490 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700491 }
492
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800493 STLDeleteElements(&mark_sweep_collectors_);
494
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700495 // If we don't reset then the mark stack complains in it's destructor.
496 allocation_stack_->Reset();
497 live_stack_->Reset();
498
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800499 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800500 // We can't take the heap lock here because there might be a daemon thread suspended with the
501 // heap lock held. We know though that no non-daemon threads are executing, and we know that
502 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
503 // those threads can't resume. We're the only running thread, and we can do whatever we like...
Ian Rogers1d54e732013-05-02 21:10:01 -0700504 STLDeleteElements(&continuous_spaces_);
505 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700506 delete gc_complete_lock_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700507 delete soft_ref_queue_lock_;
508 delete weak_ref_queue_lock_;
509 delete finalizer_ref_queue_lock_;
510 delete phantom_ref_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700511}
512
Ian Rogers1d54e732013-05-02 21:10:01 -0700513space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
514 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700515 for (const auto& space : continuous_spaces_) {
516 if (space->Contains(obj)) {
517 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700518 }
519 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700520 if (!fail_ok) {
521 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
522 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700523 return NULL;
524}
525
Ian Rogers1d54e732013-05-02 21:10:01 -0700526space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
527 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700528 for (const auto& space : discontinuous_spaces_) {
529 if (space->Contains(obj)) {
530 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700531 }
532 }
533 if (!fail_ok) {
534 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
535 }
536 return NULL;
537}
538
539space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
540 space::Space* result = FindContinuousSpaceFromObject(obj, true);
541 if (result != NULL) {
542 return result;
543 }
544 return FindDiscontinuousSpaceFromObject(obj, true);
545}
546
547space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700548 for (const auto& space : continuous_spaces_) {
549 if (space->IsImageSpace()) {
550 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700551 }
552 }
553 return NULL;
554}
555
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700556static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700557 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700558 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700559 size_t chunk_free_bytes = chunk_size - used_bytes;
560 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
561 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700562 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700563}
564
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800565mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
566 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700567 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
568 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800569 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700570
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800571 mirror::Object* obj = NULL;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700572 size_t bytes_allocated = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700573 uint64_t allocation_start = 0;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700574 if (UNLIKELY(kMeasureAllocationTime)) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700575 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700576 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700577
578 // We need to have a zygote space or else our newly allocated large object can end up in the
579 // Zygote resulting in it being prematurely freed.
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700580 // We can only do this for primitive objects since large objects will not be within the card table
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700581 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers333cf1b2013-07-24 11:57:02 -0700582 bool large_object_allocation =
583 byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray();
584 if (UNLIKELY(large_object_allocation)) {
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700585 obj = Allocate(self, large_object_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700586 // Make sure that our large object didn't get placed anywhere within the space interval or else
587 // it breaks the immune range.
588 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700589 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
590 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700591 } else {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700592 obj = Allocate(self, alloc_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700593 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700594 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700595 }
596
Mathieu Chartier037813d2012-08-23 16:44:59 -0700597 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700598 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700599
600 // Record allocation after since we want to use the atomic add for the atomic fence to guard
601 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700602 RecordAllocation(bytes_allocated, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700603
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700604 if (Dbg::IsAllocTrackingEnabled()) {
605 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700606 }
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700607 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800609 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700610 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700611 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700612 if (kDesiredHeapVerification > kNoHeapVerification) {
613 VerifyObject(obj);
614 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700615
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700616 if (UNLIKELY(kMeasureAllocationTime)) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700617 total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700618 }
619
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700620 return obj;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700621 } else {
622 std::ostringstream oss;
623 int64_t total_bytes_free = GetFreeMemory();
624 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
625 << " free bytes";
626 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
627 if (!large_object_allocation && total_bytes_free >= byte_count) {
628 size_t max_contiguous_allocation = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700629 for (const auto& space : continuous_spaces_) {
Ian Rogers333cf1b2013-07-24 11:57:02 -0700630 if (space->IsDlMallocSpace()) {
631 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
632 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800633 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700634 oss << "; failed due to fragmentation (largest possible contiguous allocation "
635 << max_contiguous_allocation << " bytes)";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700636 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700637 self->ThrowOutOfMemoryError(oss.str().c_str());
638 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700639 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700640}
641
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800642bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700643 // Note: we deliberately don't take the lock here, and mustn't test anything that would
644 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700645 if (obj == NULL) {
646 return true;
647 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700648 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700649 return false;
650 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700651 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700652}
653
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800654bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700655 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700656 if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700657 return false;
658 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700659 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
660 space::DiscontinuousSpace* d_space = NULL;
661 if (c_space != NULL) {
662 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700663 return true;
664 }
665 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700666 d_space = FindDiscontinuousSpaceFromObject(obj, true);
667 if (d_space != NULL) {
668 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700669 return true;
670 }
671 }
672 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700673 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Ian Rogers1d54e732013-05-02 21:10:01 -0700674 for (size_t i = 0; i < 5; ++i) {
675 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
676 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
677 return true;
678 }
679 NanoSleep(MsToNs(10));
680 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700681 // We need to check the bitmaps again since there is a race where we mark something as live and
682 // then clear the stack containing it.
683 if (c_space != NULL) {
684 if (c_space->GetLiveBitmap()->Test(obj)) {
685 return true;
686 }
687 } else {
688 d_space = FindDiscontinuousSpaceFromObject(obj, true);
689 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
690 return true;
691 }
692 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700693 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700694}
695
Ian Rogers04d7aa92013-03-16 14:29:17 -0700696void Heap::VerifyObjectImpl(const mirror::Object* obj) {
697 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700698 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700699 return;
700 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700701 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700702}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700703
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700704void Heap::DumpSpaces() {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700705 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700706 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
707 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700708 LOG(INFO) << space << " " << *space << "\n"
709 << live_bitmap << " " << *live_bitmap << "\n"
710 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700711 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700712 for (const auto& space : discontinuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700713 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700714 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700715}
716
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800717void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800718 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700719 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700720 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800721 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
722 return;
723 }
724 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
725 mirror::Object::ClassOffset().Int32Value();
726 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
727 if (UNLIKELY(c == NULL)) {
728 LOG(FATAL) << "Null class in object: " << obj;
729 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
730 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
731 }
732 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
733 // Note: we don't use the accessors here as they have internal sanity checks
734 // that we don't want to run
735 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
736 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
737 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
738 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
739 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700740
Ian Rogers62d6c772013-02-27 08:32:07 -0800741 if (verify_object_mode_ != kVerifyAllFast) {
742 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
743 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700744 if (!IsLiveObjectLocked(obj)) {
745 DumpSpaces();
746 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700747 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700748 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700749 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
750 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700751 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700752}
753
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800754void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700755 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700756 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700757}
758
759void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700760 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700761 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700762}
763
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700764inline void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700765 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700766 DCHECK_GT(size, 0u);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700767 num_bytes_allocated_.fetch_add(size);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700768
769 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700770 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700771 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700772 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700773
774 // TODO: Update these atomically.
775 RuntimeStats* global_stats = Runtime::Current()->GetStats();
776 ++global_stats->allocated_objects;
777 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700778 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700779
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700780 // This is safe to do since the GC will never free objects which are neither in the allocation
781 // stack or the live bitmap.
782 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700783 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700784 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700785}
786
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700787void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700788 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700789 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700790
791 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700792 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700793 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700794 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700795
796 // TODO: Do this concurrently.
797 RuntimeStats* global_stats = Runtime::Current()->GetStats();
798 global_stats->freed_objects += freed_objects;
799 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700800 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700801}
802
Mathieu Chartier720ef762013-08-17 14:46:54 -0700803inline bool Heap::IsOutOfMemoryOnAllocation(size_t alloc_size, bool grow) {
804 size_t new_footprint = num_bytes_allocated_ + alloc_size;
805 if (UNLIKELY(new_footprint > max_allowed_footprint_)) {
806 if (UNLIKELY(new_footprint > growth_limit_)) {
807 return true;
808 }
809 if (!concurrent_gc_) {
810 if (!grow) {
811 return true;
812 } else {
813 max_allowed_footprint_ = new_footprint;
814 }
815 }
816 }
817 return false;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700818}
819
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700820inline mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
821 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700822 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700823 return NULL;
824 }
825 return space->Alloc(self, alloc_size, bytes_allocated);
826}
827
828// DlMallocSpace-specific version.
829inline mirror::Object* Heap::TryToAllocate(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
830 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700831 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700832 return NULL;
833 }
Mathieu Chartier720ef762013-08-17 14:46:54 -0700834 if (LIKELY(!running_on_valgrind_)) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700835 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
836 } else {
837 return space->Alloc(self, alloc_size, bytes_allocated);
838 }
839}
840
841template <class T>
Mathieu Chartier720ef762013-08-17 14:46:54 -0700842inline mirror::Object* Heap::Allocate(Thread* self, T* space, size_t alloc_size,
843 size_t* bytes_allocated) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700844 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
845 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700846 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700847 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700848
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700849 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700850 if (ptr != NULL) {
851 return ptr;
852 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700853 return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
854}
855
Mathieu Chartier720ef762013-08-17 14:46:54 -0700856mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space,
857 size_t alloc_size, size_t* bytes_allocated) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700858 mirror::Object* ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700859
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700860 // The allocation failed. If the GC is running, block until it completes, and then retry the
861 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700862 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
863 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700864 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700865 ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700866 if (ptr != NULL) {
867 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700868 }
869 }
870
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700871 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700872 for (size_t i = static_cast<size_t>(last_gc) + 1;
873 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700874 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700875 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700876 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700877 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700878 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700879 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
880 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700881 break;
882 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700883 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700884 run_gc = have_zygote_space_;
885 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700886 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700887 run_gc = true;
888 break;
889 default:
890 break;
891 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700892
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700893 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700894 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700895 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800896 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700897 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700898
899 // Did we free sufficient memory for the allocation to succeed?
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700900 ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700901 if (ptr != NULL) {
902 return ptr;
903 }
904 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700905 }
906
907 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700908 // Try harder, growing the heap if necessary.
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700909 ptr = TryToAllocate(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700910 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700911 return ptr;
912 }
913
Elliott Hughes81ff3182012-03-23 20:35:56 -0700914 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
915 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
916 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700917
Elliott Hughes418dfe72011-10-06 18:56:27 -0700918 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700919 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
920 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700921
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700922 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700923 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700924 return TryToAllocate(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700925}
926
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700927void Heap::SetTargetHeapUtilization(float target) {
928 DCHECK_GT(target, 0.0f); // asserted in Java code
929 DCHECK_LT(target, 1.0f);
930 target_utilization_ = target;
931}
932
Ian Rogers1d54e732013-05-02 21:10:01 -0700933size_t Heap::GetObjectsAllocated() const {
934 size_t total = 0;
935 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
936 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
937 space::ContinuousSpace* space = *it;
938 if (space->IsDlMallocSpace()) {
939 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700940 }
941 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700942 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
943 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
944 space::DiscontinuousSpace* space = *it;
945 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
946 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700947 return total;
948}
949
Ian Rogers1d54e732013-05-02 21:10:01 -0700950size_t Heap::GetObjectsAllocatedEver() const {
951 size_t total = 0;
952 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
953 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
954 space::ContinuousSpace* space = *it;
955 if (space->IsDlMallocSpace()) {
956 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700957 }
958 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700959 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
960 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
961 space::DiscontinuousSpace* space = *it;
962 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
963 }
964 return total;
965}
966
967size_t Heap::GetBytesAllocatedEver() const {
968 size_t total = 0;
969 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
970 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
971 space::ContinuousSpace* space = *it;
972 if (space->IsDlMallocSpace()) {
973 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
974 }
975 }
976 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
977 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
978 space::DiscontinuousSpace* space = *it;
979 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
980 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700981 return total;
982}
983
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700984class InstanceCounter {
985 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800986 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700987 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800988 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700989 }
990
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800991 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800992 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800993 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800994 if (use_is_assignable_from_) {
995 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
996 ++counts_[i];
997 }
998 } else {
999 if (instance_class == classes_[i]) {
1000 ++counts_[i];
1001 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001002 }
1003 }
1004 }
1005
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001006 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001007 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001008 bool use_is_assignable_from_;
1009 uint64_t* const counts_;
1010
1011 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001012};
1013
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001014void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001015 uint64_t* counts) {
1016 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1017 // is empty, so the live bitmap is the only place we need to look.
1018 Thread* self = Thread::Current();
1019 self->TransitionFromRunnableToSuspended(kNative);
1020 CollectGarbage(false);
1021 self->TransitionFromSuspendedToRunnable();
1022
1023 InstanceCounter counter(classes, use_is_assignable_from, counts);
1024 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001025 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001026}
1027
Elliott Hughes3b78c942013-01-15 17:35:41 -08001028class InstanceCollector {
1029 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001030 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001031 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1032 : class_(c), max_count_(max_count), instances_(instances) {
1033 }
1034
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001035 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1036 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001037 if (instance_class == class_) {
1038 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001039 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001040 }
1041 }
1042 }
1043
1044 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001045 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001046 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001047 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001048
1049 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1050};
1051
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001052void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1053 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001054 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1055 // is empty, so the live bitmap is the only place we need to look.
1056 Thread* self = Thread::Current();
1057 self->TransitionFromRunnableToSuspended(kNative);
1058 CollectGarbage(false);
1059 self->TransitionFromSuspendedToRunnable();
1060
1061 InstanceCollector collector(c, max_count, instances);
1062 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1063 GetLiveBitmap()->Visit(collector);
1064}
1065
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001066class ReferringObjectsFinder {
1067 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001068 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1069 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001070 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1071 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1072 }
1073
1074 // For bitmap Visit.
1075 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1076 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001077 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001078 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001079 }
1080
1081 // For MarkSweep::VisitObjectReferences.
Brian Carlstromdf629502013-07-17 22:39:56 -07001082 void operator()(const mirror::Object* referrer, const mirror::Object* object,
1083 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001084 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001085 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001086 }
1087 }
1088
1089 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001090 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001091 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001092 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001093
1094 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1095};
1096
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001097void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1098 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001099 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1100 // is empty, so the live bitmap is the only place we need to look.
1101 Thread* self = Thread::Current();
1102 self->TransitionFromRunnableToSuspended(kNative);
1103 CollectGarbage(false);
1104 self->TransitionFromSuspendedToRunnable();
1105
1106 ReferringObjectsFinder finder(o, max_count, referring_objects);
1107 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1108 GetLiveBitmap()->Visit(finder);
1109}
1110
Ian Rogers30fab402012-01-23 15:43:46 -08001111void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001112 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1113 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001114 Thread* self = Thread::Current();
1115 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001116 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001117}
1118
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001119void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001120 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001121 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1122 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001123 Thread* self = Thread::Current();
1124 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001125
1126 // Try to see if we have any Zygote spaces.
1127 if (have_zygote_space_) {
1128 return;
1129 }
1130
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001131 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1132
1133 {
1134 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001135 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001136 FlushAllocStack();
1137 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001138
Ian Rogers1d54e732013-05-02 21:10:01 -07001139 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1140 // of the remaining available heap memory.
1141 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001142 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -07001143 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001144
Ian Rogers1d54e732013-05-02 21:10:01 -07001145 // Change the GC retention policy of the zygote space to only collect when full.
1146 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1147 AddContinuousSpace(alloc_space_);
1148 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001149
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001150 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001151 for (const auto& collector : mark_sweep_collectors_) {
1152 collector->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001153 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001154}
1155
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001156void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001157 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1158 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001159 allocation_stack_->Reset();
1160}
1161
Ian Rogers1d54e732013-05-02 21:10:01 -07001162void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1163 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001164 mirror::Object** limit = stack->End();
1165 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1166 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001167 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001168 if (LIKELY(bitmap->HasAddress(obj))) {
1169 bitmap->Set(obj);
1170 } else {
1171 large_objects->Set(obj);
1172 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001173 }
1174}
1175
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001176
1177const char* gc_cause_and_type_strings[3][4] = {
1178 {"", "GC Alloc Sticky", "GC Alloc Partial", "GC Alloc Full"},
1179 {"", "GC Background Sticky", "GC Background Partial", "GC Background Full"},
1180 {"", "GC Explicit Sticky", "GC Explicit Partial", "GC Explicit Full"}};
1181
Ian Rogers1d54e732013-05-02 21:10:01 -07001182collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1183 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001184 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001185
Mathieu Chartier65db8802012-11-20 12:36:46 -08001186 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001187 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001188
Ian Rogers120f1c72012-09-28 17:17:10 -07001189 if (self->IsHandlingStackOverflow()) {
1190 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1191 }
1192
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001193 // Ensure there is only one GC at a time.
1194 bool start_collect = false;
1195 while (!start_collect) {
1196 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001197 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001198 if (!is_gc_running_) {
1199 is_gc_running_ = true;
1200 start_collect = true;
1201 }
1202 }
1203 if (!start_collect) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001204 // TODO: timinglog this.
Ian Rogers81d425b2012-09-27 16:03:43 -07001205 WaitForConcurrentGcToComplete(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001206
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001207 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1208 // Not doing at the moment to ensure soft references are cleared.
1209 }
1210 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001211 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001212
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001213 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1214 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1215 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1216 }
1217
Ian Rogers1d54e732013-05-02 21:10:01 -07001218 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001219 uint64_t gc_start_size = GetBytesAllocated();
1220 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001221 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001222 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1223 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001224 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001225 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001226 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001227 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1228 }
1229
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001230 if (gc_type == collector::kGcTypeSticky &&
1231 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1232 gc_type = collector::kGcTypePartial;
1233 }
1234
Ian Rogers1d54e732013-05-02 21:10:01 -07001235 DCHECK_LT(gc_type, collector::kGcTypeMax);
1236 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001237 DCHECK_LE(gc_cause, kGcCauseExplicit);
1238
1239 ATRACE_BEGIN(gc_cause_and_type_strings[gc_cause][gc_type]);
1240
Ian Rogers1d54e732013-05-02 21:10:01 -07001241 collector::MarkSweep* collector = NULL;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001242 for (const auto& cur_collector : mark_sweep_collectors_) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001243 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1244 collector = cur_collector;
1245 break;
1246 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001247 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001248 CHECK(collector != NULL)
1249 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1250 << " and type=" << gc_type;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001251
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001252 collector->clear_soft_references_ = clear_soft_references;
1253 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001254 total_objects_freed_ever_ += collector->GetFreedObjects();
1255 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001256 if (care_about_pause_times_) {
1257 const size_t duration = collector->GetDurationNs();
1258 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1259 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001260 bool was_slow = duration > long_gc_log_threshold_ ||
1261 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001262 if (!was_slow) {
1263 for (uint64_t pause : pauses) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001264 was_slow = was_slow || pause > long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001265 }
1266 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001267
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001268 if (was_slow) {
1269 const size_t percent_free = GetPercentFree();
1270 const size_t current_heap_size = GetBytesAllocated();
1271 const size_t total_memory = GetTotalMemory();
1272 std::ostringstream pause_string;
1273 for (size_t i = 0; i < pauses.size(); ++i) {
1274 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1275 << ((i != pauses.size() - 1) ? ", " : "");
1276 }
1277 LOG(INFO) << gc_cause << " " << collector->GetName()
1278 << " GC freed " << collector->GetFreedObjects() << "("
1279 << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1280 << collector->GetFreedLargeObjects() << "("
1281 << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1282 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1283 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1284 << " total " << PrettyDuration((duration / 1000) * 1000);
1285 if (VLOG_IS_ON(heap)) {
1286 LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
1287 }
1288 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001289 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001290
Ian Rogers15bf2d32012-08-28 17:33:04 -07001291 {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001292 MutexLock mu(self, *gc_complete_lock_);
1293 is_gc_running_ = false;
1294 last_gc_type_ = gc_type;
1295 // Wake anyone who may have been waiting for the GC to complete.
1296 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001297 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001298
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001299 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001300
1301 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001302 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001303 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001304}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001305
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001306void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::TimingLogger& timings,
Ian Rogers1d54e732013-05-02 21:10:01 -07001307 collector::GcType gc_type) {
1308 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001309 // Don't need to do anything for mod union table in this case since we are only scanning dirty
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001310 // cards.
1311 return;
1312 }
1313
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001314 base::TimingLogger::ScopedSplit split("UpdateModUnionTable", &timings);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001315 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001316 if (gc_type == collector::kGcTypePartial) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001317 base::TimingLogger::ScopedSplit split("UpdateZygoteModUnionTable", &timings);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001318 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001319
Ian Rogers1d54e732013-05-02 21:10:01 -07001320 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001321 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001322 }
1323
1324 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001325 timings.NewSplit("UpdateModUnionTable");
1326 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001327
1328 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001329 timings.NewSplit("MarkImageToAllocSpaceReferences");
1330 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001331}
1332
Ian Rogers1d54e732013-05-02 21:10:01 -07001333static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001334 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001335 if (root == obj) {
1336 LOG(INFO) << "Object " << obj << " is a root";
1337 }
1338}
1339
1340class ScanVisitor {
1341 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001342 void operator()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001343 LOG(INFO) << "Would have rescanned object " << obj;
1344 }
1345};
1346
Ian Rogers1d54e732013-05-02 21:10:01 -07001347// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001348class VerifyReferenceVisitor {
1349 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001350 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001351 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001352 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001353
1354 bool Failed() const {
1355 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001356 }
1357
1358 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001359 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001360 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1361 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001362 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001363 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001364 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1365 accounting::CardTable* card_table = heap_->GetCardTable();
1366 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1367 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001368
Ian Rogers1d54e732013-05-02 21:10:01 -07001369 if (obj != NULL) {
1370 byte* card_addr = card_table->CardFromAddr(obj);
1371 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1372 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1373 << "\nObj type " << PrettyTypeOf(obj)
1374 << "\nRef type " << PrettyTypeOf(ref);
1375 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1376 void* cover_begin = card_table->AddrFromCard(card_addr);
1377 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1378 accounting::CardTable::kCardSize);
1379 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1380 << "-" << cover_end;
1381 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001382
Ian Rogers1d54e732013-05-02 21:10:01 -07001383 // Print out how the object is live.
1384 if (bitmap != NULL && bitmap->Test(obj)) {
1385 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1386 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001387 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001388 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1389 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001390 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001391 LOG(ERROR) << "Object " << obj << " found in live stack";
1392 }
1393 // Attempt to see if the card table missed the reference.
1394 ScanVisitor scan_visitor;
1395 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1396 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001397 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001398
1399 // Search to see if any of the roots reference our object.
1400 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1401 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1402
1403 // Search to see if any of the roots reference our reference.
1404 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1405 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1406 } else {
1407 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001408 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001409 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001410 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001411 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001412 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001413 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001414 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001415 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1416 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1417 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001418 }
1419 }
1420
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001421 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001422 return heap_->IsLiveObjectLocked(obj);
1423 }
1424
1425 static void VerifyRoots(const mirror::Object* root, void* arg) {
1426 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1427 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001428 }
1429
1430 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001431 Heap* const heap_;
1432 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001433};
1434
Ian Rogers1d54e732013-05-02 21:10:01 -07001435// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001436class VerifyObjectVisitor {
1437 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001438 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001439
Brian Carlstromdf629502013-07-17 22:39:56 -07001440 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001441 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001442 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1443 // be live or else how did we find it in the live bitmap?
1444 VerifyReferenceVisitor visitor(heap_);
1445 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1446 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001447 }
1448
1449 bool Failed() const {
1450 return failed_;
1451 }
1452
1453 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001454 Heap* const heap_;
1455 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001456};
1457
1458// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001459bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001460 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001461 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001462 allocation_stack_->Sort();
1463 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001464 // Perform the verification.
1465 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001466 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001467 GetLiveBitmap()->Visit(visitor);
1468 // We don't want to verify the objects in the allocation stack since they themselves may be
1469 // pointing to dead objects if they are not reachable.
1470 if (visitor.Failed()) {
1471 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001472 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001473 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001474 return true;
1475}
1476
1477class VerifyReferenceCardVisitor {
1478 public:
1479 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1480 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1481 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001482 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001483 }
1484
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001485 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1486 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001487 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1488 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001489 // Filter out class references since changing an object's class does not mark the card as dirty.
1490 // Also handles large objects, since the only reference they hold is a class reference.
1491 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001492 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001493 // If the object is not dirty and it is referencing something in the live stack other than
1494 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001495 if (!card_table->AddrIsInCardTable(obj)) {
1496 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1497 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001498 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001499 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1500 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001501 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001502 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1503 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001504 LOG(ERROR) << "Object " << obj << " found in live stack";
1505 }
1506 if (heap_->GetLiveBitmap()->Test(obj)) {
1507 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1508 }
1509 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1510 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1511
1512 // Print which field of the object is dead.
1513 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001514 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001515 CHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001516 const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
1517 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001518 CHECK(fields != NULL);
1519 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001520 const mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001521 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1522 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1523 << PrettyField(cur);
1524 break;
1525 }
1526 }
1527 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001528 const mirror::ObjectArray<mirror::Object>* object_array =
1529 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001530 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1531 if (object_array->Get(i) == ref) {
1532 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1533 }
1534 }
1535 }
1536
1537 *failed_ = true;
1538 }
1539 }
1540 }
1541 }
1542
1543 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001544 Heap* const heap_;
1545 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001546};
1547
1548class VerifyLiveStackReferences {
1549 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001550 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001551 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001552 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001553
Brian Carlstromdf629502013-07-17 22:39:56 -07001554 void operator()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001555 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1556 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001557 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001558 }
1559
1560 bool Failed() const {
1561 return failed_;
1562 }
1563
1564 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001565 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001566 bool failed_;
1567};
1568
1569bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001570 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001571
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001572 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001573 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001574 VerifyLiveStackReferences visitor(this);
1575 GetLiveBitmap()->Visit(visitor);
1576
1577 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001578 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001579 visitor(*it);
1580 }
1581
1582 if (visitor.Failed()) {
1583 DumpSpaces();
1584 return false;
1585 }
1586 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001587}
1588
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001589void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001590 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001591
1592 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001593 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001594 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001595 }
1596}
1597
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001598void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001599 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001600 for (const auto& space : continuous_spaces_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001601 if (space->IsImageSpace()) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001602 base::TimingLogger::ScopedSplit split("ImageModUnionClearCards", &timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07001603 image_mod_union_table_->ClearCards(space);
1604 } else if (space->IsZygoteSpace()) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001605 base::TimingLogger::ScopedSplit split("ZygoteModUnionClearCards", &timings);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001606 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001607 } else {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001608 base::TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001609 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1610 // were dirty before the GC started.
1611 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001612 }
1613 }
1614}
1615
Ian Rogers1d54e732013-05-02 21:10:01 -07001616void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001617 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1618 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001619
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001620 if (verify_pre_gc_heap_) {
1621 thread_list->SuspendAll();
1622 {
1623 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1624 if (!VerifyHeapReferences()) {
1625 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1626 }
1627 }
1628 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001629 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001630
1631 // Check that all objects which reference things in the live stack are on dirty cards.
1632 if (verify_missing_card_marks_) {
1633 thread_list->SuspendAll();
1634 {
1635 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1636 SwapStacks();
1637 // Sort the live stack so that we can quickly binary search it later.
1638 if (!VerifyMissingCardMarks()) {
1639 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1640 }
1641 SwapStacks();
1642 }
1643 thread_list->ResumeAll();
1644 }
1645
1646 if (verify_mod_union_table_) {
1647 thread_list->SuspendAll();
1648 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1649 zygote_mod_union_table_->Update();
1650 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001651 image_mod_union_table_->Update();
1652 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001653 thread_list->ResumeAll();
1654 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001655}
1656
Ian Rogers1d54e732013-05-02 21:10:01 -07001657void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001658 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1659 // reachable objects.
1660 if (verify_post_gc_heap_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001661 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001662 Thread* self = Thread::Current();
1663 CHECK_NE(self->GetState(), kRunnable);
1664 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001665 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001666 {
1667 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1668 // Swapping bound bitmaps does nothing.
1669 gc->SwapBitmaps();
1670 if (!VerifyHeapReferences()) {
1671 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1672 }
1673 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001674 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001675 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001676 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001677 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001678}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001679
Ian Rogers1d54e732013-05-02 21:10:01 -07001680void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001681 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001682 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001683 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001684 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001685 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001686 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001687}
1688
Ian Rogers1d54e732013-05-02 21:10:01 -07001689collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1690 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001691 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001692 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001693 bool do_wait;
1694 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001695 {
1696 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001697 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001698 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001699 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001700 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001701 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001702 // We must wait, change thread state then sleep on gc_complete_cond_;
1703 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1704 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001705 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001706 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001707 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001708 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001709 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001710 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001711 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001712 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001713 if (wait_time > long_pause_log_threshold_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001714 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1715 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001716 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001717 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001718 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001719 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001720}
1721
Elliott Hughesc967f782012-04-16 10:23:15 -07001722void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001723 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001724 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001725 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001726}
1727
1728size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001729 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001730}
1731
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001732void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001733 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001734 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001735 << PrettySize(GetMaxMemory());
1736 max_allowed_footprint = GetMaxMemory();
1737 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001738 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001739}
1740
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001741void Heap::UpdateMaxNativeFootprint() {
1742 size_t native_size = native_bytes_allocated_;
1743 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1744 size_t target_size = native_size / GetTargetHeapUtilization();
1745 if (target_size > native_size + max_free_) {
1746 target_size = native_size + max_free_;
1747 } else if (target_size < native_size + min_free_) {
1748 target_size = native_size + min_free_;
1749 }
1750 native_footprint_gc_watermark_ = target_size;
1751 native_footprint_limit_ = 2 * target_size - native_size;
1752}
1753
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001754void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001755 // We know what our utilization is at this moment.
1756 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001757 const size_t bytes_allocated = GetBytesAllocated();
1758 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001759 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001760
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001761 size_t target_size;
1762 if (gc_type != collector::kGcTypeSticky) {
1763 // Grow the heap for non sticky GC.
1764 target_size = bytes_allocated / GetTargetHeapUtilization();
1765 if (target_size > bytes_allocated + max_free_) {
1766 target_size = bytes_allocated + max_free_;
1767 } else if (target_size < bytes_allocated + min_free_) {
1768 target_size = bytes_allocated + min_free_;
1769 }
1770 next_gc_type_ = collector::kGcTypeSticky;
1771 } else {
1772 // Based on how close the current heap size is to the target size, decide
1773 // whether or not to do a partial or sticky GC next.
1774 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1775 next_gc_type_ = collector::kGcTypeSticky;
1776 } else {
1777 next_gc_type_ = collector::kGcTypePartial;
1778 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001779
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001780 // If we have freed enough memory, shrink the heap back down.
1781 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1782 target_size = bytes_allocated + max_free_;
1783 } else {
1784 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1785 }
1786 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001787
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001788 if (!ignore_max_footprint_) {
1789 SetIdealFootprint(target_size);
1790
1791 if (concurrent_gc_) {
1792 // Calculate when to perform the next ConcurrentGC.
1793
1794 // Calculate the estimated GC duration.
1795 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1796 // Estimate how many remaining bytes we will have when we need to start the next GC.
1797 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1798 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1799 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1800 // A never going to happen situation that from the estimated allocation rate we will exceed
1801 // the applications entire footprint with the given estimated allocation rate. Schedule
1802 // another GC straight away.
1803 concurrent_start_bytes_ = bytes_allocated;
1804 } else {
1805 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1806 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1807 // right away.
1808 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1809 }
1810 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1811 DCHECK_LE(max_allowed_footprint_, growth_limit_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001812 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001813 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001814
1815 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001816}
1817
jeffhaoc1160702011-10-27 15:48:45 -07001818void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001819 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001820 alloc_space_->ClearGrowthLimit();
1821}
1822
Elliott Hughesadb460d2011-10-05 17:02:34 -07001823void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001824 MemberOffset reference_queue_offset,
1825 MemberOffset reference_queueNext_offset,
1826 MemberOffset reference_pendingNext_offset,
1827 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001828 reference_referent_offset_ = reference_referent_offset;
1829 reference_queue_offset_ = reference_queue_offset;
1830 reference_queueNext_offset_ = reference_queueNext_offset;
1831 reference_pendingNext_offset_ = reference_pendingNext_offset;
1832 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1833 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1834 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1835 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1836 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1837 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1838}
1839
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001840mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001841 DCHECK(reference != NULL);
1842 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001843 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001844}
1845
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001846void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001847 DCHECK(reference != NULL);
1848 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1849 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1850}
1851
1852// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001853bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001854 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001855 const mirror::Object* queue =
1856 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1857 const mirror::Object* queue_next =
1858 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001859 return (queue != NULL) && (queue_next == NULL);
1860}
1861
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001862void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001863 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001864 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1865 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001866 EnqueuePendingReference(ref, cleared_reference_list);
1867}
1868
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001869void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001870 DCHECK(ref != NULL);
1871 DCHECK(list != NULL);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001872 mirror::Object* pending =
1873 ref->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
1874 if (pending == NULL) {
1875 if (*list == NULL) {
1876 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1877 *list = ref;
1878 } else {
1879 mirror::Object* head =
1880 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
1881 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1882 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1883 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001884 }
1885}
1886
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001887mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001888 DCHECK(list != NULL);
1889 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001890 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1891 false);
1892 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001893
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001894 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1895 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001896 if (*list == head) {
1897 ref = *list;
1898 *list = NULL;
1899 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001900 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1901 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001902 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1903 ref = head;
1904 }
1905 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1906 return ref;
1907}
1908
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001909void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001910 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001911 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001912 ArgArray arg_array(NULL, 0);
1913 arg_array.Append(reinterpret_cast<uint32_t>(object));
1914 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001915 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001916}
1917
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001918void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001919 DCHECK(cleared != NULL);
1920 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001921 // When a runtime isn't started there are no reference queues to care about so ignore.
1922 if (LIKELY(Runtime::Current()->IsStarted())) {
1923 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001924 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001925 ArgArray arg_array(NULL, 0);
1926 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1927 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001928 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001929 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001930 *cleared = NULL;
1931 }
1932}
1933
Ian Rogers1f539342012-10-03 21:09:42 -07001934void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001935 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001936 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001937 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001938 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001939 !runtime->IsConcurrentGcEnabled()) {
1940 return;
1941 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001942 {
1943 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1944 if (runtime->IsShuttingDown()) {
1945 return;
1946 }
1947 }
1948 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001949 return;
1950 }
1951
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001952 // We already have a request pending, no reason to start more until we update
1953 // concurrent_start_bytes_.
1954 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1955
Ian Rogers120f1c72012-09-28 17:17:10 -07001956 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001957 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1958 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001959 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1960 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001961 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001962}
1963
Ian Rogers81d425b2012-09-27 16:03:43 -07001964void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001965 {
1966 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001967 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001968 return;
1969 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001970 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001971
Mathieu Chartier65db8802012-11-20 12:36:46 -08001972 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001973 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001974 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001975 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001976}
1977
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001978void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001979 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1980 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1981 // a space it will hold its lock and can become a cause of jank.
1982 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1983 // forking.
1984
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001985 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1986 // because that only marks object heads, so a large array looks like lots of empty space. We
1987 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1988 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1989 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1990 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001991 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001992 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001993 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
Mathieu Chartiere0a53e92013-08-05 10:17:40 -07001994 if ((utilization > 0.75f && !IsLowMemoryMode()) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
1995 // Don't bother trimming the alloc space if it's more than 75% utilized and low memory mode is
1996 // not enabled, or if a heap trim occurred in the last two seconds.
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001997 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001998 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001999
2000 Thread* self = Thread::Current();
2001 {
2002 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2003 Runtime* runtime = Runtime::Current();
2004 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2005 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2006 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2007 // as we don't hold the lock while requesting the trim).
2008 return;
2009 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002010 }
Ian Rogers48931882013-01-22 14:35:16 -08002011
Ian Rogers1d54e732013-05-02 21:10:01 -07002012 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002013 ListenForProcessStateChange();
2014
2015 // Trim only if we do not currently care about pause times.
2016 if (!care_about_pause_times_) {
2017 JNIEnv* env = self->GetJniEnv();
2018 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2019 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2020 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2021 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2022 CHECK(!env->ExceptionCheck());
2023 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002024}
2025
Ian Rogers48931882013-01-22 14:35:16 -08002026size_t Heap::Trim() {
2027 // Handle a requested heap trim on a thread outside of the main GC thread.
2028 return alloc_space_->Trim();
2029}
2030
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002031bool Heap::IsGCRequestPending() const {
2032 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2033}
2034
2035void Heap::RegisterNativeAllocation(int bytes) {
2036 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002037 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002038 Thread* self = Thread::Current();
2039 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
2040 // The second watermark is higher than the gc watermark. If you hit this it means you are
2041 // allocating native objects faster than the GC can keep up with.
2042 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2043 JNIEnv* env = self->GetJniEnv();
2044 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
2045 // point.
2046 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
2047 DCHECK(WellKnownClasses::java_lang_System != NULL);
2048 WellKnownClasses::java_lang_System_runFinalization =
2049 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2050 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
2051 }
2052 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
2053 // Just finished a GC, attempt to run finalizers.
2054 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2055 WellKnownClasses::java_lang_System_runFinalization);
2056 CHECK(!env->ExceptionCheck());
2057 }
2058
2059 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2060 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2061 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
2062 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2063 WellKnownClasses::java_lang_System_runFinalization);
2064 CHECK(!env->ExceptionCheck());
2065 }
2066 // We have just run finalizers, update the native watermark since it is very likely that
2067 // finalizers released native managed allocations.
2068 UpdateMaxNativeFootprint();
2069 } else {
2070 if (!IsGCRequestPending()) {
2071 RequestConcurrentGC(self);
2072 }
2073 }
2074 }
2075}
2076
2077void Heap::RegisterNativeFree(int bytes) {
2078 int expected_size, new_size;
2079 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002080 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002081 new_size = expected_size - bytes;
2082 if (new_size < 0) {
2083 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
2084 bytes, expected_size);
2085 break;
2086 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002087 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002088}
2089
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002090int64_t Heap::GetTotalMemory() const {
2091 int64_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002092 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002093 if (space->IsImageSpace()) {
2094 // Currently don't include the image space.
2095 } else if (space->IsDlMallocSpace()) {
2096 // Zygote or alloc space
2097 ret += space->AsDlMallocSpace()->GetFootprint();
2098 }
2099 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002100 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002101 if (space->IsLargeObjectSpace()) {
2102 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2103 }
2104 }
2105 return ret;
2106}
2107
Ian Rogers1d54e732013-05-02 21:10:01 -07002108} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002109} // namespace art