blob: a9e5b085087cfaf51483169bca6e386456198f27 [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>
24
Elliott Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070026#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080027#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070028#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070029#include "gc/accounting/atomic_stack.h"
30#include "gc/accounting/card_table-inl.h"
31#include "gc/accounting/heap_bitmap-inl.h"
32#include "gc/accounting/mod_union_table-inl.h"
33#include "gc/accounting/space_bitmap-inl.h"
34#include "gc/collector/mark_sweep-inl.h"
35#include "gc/collector/partial_mark_sweep.h"
36#include "gc/collector/sticky_mark_sweep.h"
37#include "gc/space/image_space.h"
38#include "gc/space/large_object_space.h"
39#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070040#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080041#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/class-inl.h"
43#include "mirror/field-inl.h"
44#include "mirror/object.h"
45#include "mirror/object-inl.h"
46#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080047#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080048#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070049#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070050#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070051#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070052#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070053#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070054#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070055
56namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070057namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070058
Ian Rogers1d54e732013-05-02 21:10:01 -070059// When to create a log message about a slow GC, 100ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080060static const uint64_t kSlowGcThreshold = MsToNs(100);
Mathieu Chartier82353312013-07-18 10:47:51 -070061// When to create a log message about a long pause, 5ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080062static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier0418ae22013-07-31 13:35:46 -070063static const bool kGCALotMode = false;
64static const size_t kGcAlotInterval = KB;
Mathieu Chartier65db8802012-11-20 12:36:46 -080065static const bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070066// Minimum amount of remaining bytes before a concurrent GC is triggered.
67static const size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070068const double Heap::kDefaultTargetUtilization = 0.5;
69
Mathieu Chartier0051be62012-10-12 17:47:11 -070070Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070071 double target_utilization, size_t capacity, const std::string& original_image_file_name,
72 bool concurrent_gc, size_t num_gc_threads, bool low_memory_mode)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070073 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080074 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070075 concurrent_gc_(concurrent_gc),
Mathieu Chartier63a54342013-07-23 13:17:59 -070076 num_gc_threads_(num_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070077 low_memory_mode_(low_memory_mode),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070078 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070079 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080080 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070081 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070082 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080083 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070084 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070085 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070086 native_footprint_gc_watermark_(initial_size),
87 native_footprint_limit_(2 * initial_size),
Mathieu Chartierc39e3422013-08-07 16:41:36 -070088 activity_thread_class_(NULL),
89 application_thread_class_(NULL),
90 activity_thread_(NULL),
91 application_thread_(NULL),
92 last_process_state_id_(NULL),
93 // Initially care about pauses in case we never get notified of process states, or if the JNI
94 // code becomes broken.
95 care_about_pause_times_(true),
Ian Rogers1d54e732013-05-02 21:10:01 -070096 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
97 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -070098 total_bytes_freed_ever_(0),
99 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700100 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800101 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700102 native_bytes_allocated_(0),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700103 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700104 verify_missing_card_marks_(false),
105 verify_system_weaks_(false),
106 verify_pre_gc_heap_(false),
107 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700108 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700109 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700110 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700111 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800112 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700113 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
114 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
115 * verification is enabled, we limit the size of allocation stacks to speed up their
116 * searching.
117 */
118 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
119 : (kDesiredHeapVerification > kNoHeapVerification) ? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800120 reference_referent_offset_(0),
121 reference_queue_offset_(0),
122 reference_queueNext_offset_(0),
123 reference_pendingNext_offset_(0),
124 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700125 min_free_(min_free),
126 max_free_(max_free),
127 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700128 total_wait_time_(0),
129 measure_allocation_time_(false),
130 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700131 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800132 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800133 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700134 }
135
Ian Rogers1d54e732013-05-02 21:10:01 -0700136 live_bitmap_.reset(new accounting::HeapBitmap(this));
137 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700138
Ian Rogers30fab402012-01-23 15:43:46 -0800139 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700140 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800141 std::string image_file_name(original_image_file_name);
142 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700143 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
144 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700145 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800146 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
147 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800148 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
149 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700150 if (oat_file_end_addr > requested_alloc_space_begin) {
151 requested_alloc_space_begin =
152 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
153 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700154 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700155 }
156
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700157 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700158 const bool kUseFreeListSpaceForLOS = false;
159 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700160 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700161 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700162 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700163 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700164 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
165 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700166
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700167 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700168 initial_size,
169 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700170 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700171 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700172 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700173 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700174
Ian Rogers1d54e732013-05-02 21:10:01 -0700175 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
176 byte* heap_begin = continuous_spaces_.front()->Begin();
177 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
178 if (continuous_spaces_.back()->IsDlMallocSpace()) {
179 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700180 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700181
Ian Rogers30fab402012-01-23 15:43:46 -0800182 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700183 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700184 typedef std::vector<space::ContinuousSpace*>::iterator It;
185 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
186 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800187 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700188 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700189 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800190 }
191 }
192
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800193 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700194 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700195 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700196
Mathieu Chartier161a8e02013-08-01 19:12:52 -0700197 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
Ian Rogers1d54e732013-05-02 21:10:01 -0700198 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700199
Ian Rogers1d54e732013-05-02 21:10:01 -0700200 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700201 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700202
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700203 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700204 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700205
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800206 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700207 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700208 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
209 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
210 max_allocation_stack_size_));
211 live_stack_.reset(accounting::ObjectStack::Create("live stack",
212 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700213
Mathieu Chartier65db8802012-11-20 12:36:46 -0800214 // It's still too early to take a lock because there are no threads yet, but we can create locks
215 // now. We don't create it earlier to make it clear that you can't use locks during heap
216 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700217 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700218 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
219 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700220
Mathieu Chartier63a54342013-07-23 13:17:59 -0700221 // Create the reference queue lock, this is required so for parallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700222 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700223
Ian Rogers1d54e732013-05-02 21:10:01 -0700224 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800225 last_gc_size_ = GetBytesAllocated();
226
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800227 // Create our garbage collectors.
228 for (size_t i = 0; i < 2; ++i) {
229 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700230 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
231 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
232 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700233 }
234
Brian Carlstrom42748892013-07-18 18:04:08 -0700235 CHECK_NE(max_allowed_footprint_, 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800236 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800237 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700238 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700239}
240
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700241void Heap::CreateThreadPool() {
Mathieu Chartier63a54342013-07-23 13:17:59 -0700242 thread_pool_.reset(new ThreadPool(num_gc_threads_));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700243}
244
245void Heap::DeleteThreadPool() {
246 thread_pool_.reset(NULL);
247}
248
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700249// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700250struct ContinuousSpaceSorter {
Brian Carlstromdf629502013-07-17 22:39:56 -0700251 bool operator()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700252 return a->Begin() < b->Begin();
253 }
254};
255
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700256static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
257 CHECK(out_value != NULL);
258 jfieldID field = env->GetStaticFieldID(clz, name, "I");
259 if (field == NULL) {
260 env->ExceptionClear();
261 return false;
262 }
263 *out_value = env->GetStaticIntField(clz, field);
264 return true;
265}
266
267void Heap::ListenForProcessStateChange() {
268 VLOG(gc) << "Heap notified of process state change";
269
270 Thread* self = Thread::Current();
271 JNIEnvExt* env = self->GetJniEnv();
272
273 if (!have_zygote_space_) {
274 return;
275 }
276
277 if (activity_thread_class_ == NULL) {
278 jclass clz = env->FindClass("android/app/ActivityThread");
279 if (clz == NULL) {
280 env->ExceptionClear();
281 LOG(WARNING) << "Could not find activity thread class in process state change";
282 return;
283 }
284 activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
285 }
286
287 if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
288 jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
289 "currentActivityThread",
290 "()Landroid/app/ActivityThread;");
291 if (current_activity_method == NULL) {
292 env->ExceptionClear();
293 LOG(WARNING) << "Could not get method for currentActivityThread";
294 return;
295 }
296
297 jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
298 if (obj == NULL) {
299 env->ExceptionClear();
300 LOG(WARNING) << "Could not get current activity";
301 return;
302 }
303 activity_thread_ = env->NewGlobalRef(obj);
304 }
305
306 if (process_state_cares_about_pause_time_.empty()) {
307 // Just attempt to do this the first time.
308 jclass clz = env->FindClass("android/app/ActivityManager");
309 if (clz == NULL) {
310 LOG(WARNING) << "Activity manager class is null";
311 return;
312 }
313 ScopedLocalRef<jclass> activity_manager(env, clz);
314 std::vector<const char*> care_about_pauses;
315 care_about_pauses.push_back("PROCESS_STATE_TOP");
316 care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
317 // Attempt to read the constants and classify them as whether or not we care about pause times.
318 for (size_t i = 0; i < care_about_pauses.size(); ++i) {
319 int process_state = 0;
320 if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
321 process_state_cares_about_pause_time_.insert(process_state);
322 VLOG(gc) << "Adding process state " << process_state
323 << " to set of states which care about pause time";
324 }
325 }
326 }
327
328 if (application_thread_class_ == NULL) {
329 jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
330 if (clz == NULL) {
331 env->ExceptionClear();
332 LOG(WARNING) << "Could not get application thread class";
333 return;
334 }
335 application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
336 last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
337 if (last_process_state_id_ == NULL) {
338 env->ExceptionClear();
339 LOG(WARNING) << "Could not get last process state member";
340 return;
341 }
342 }
343
344 if (application_thread_class_ != NULL && application_thread_ == NULL) {
345 jmethodID get_application_thread =
346 env->GetMethodID(activity_thread_class_, "getApplicationThread",
347 "()Landroid/app/ActivityThread$ApplicationThread;");
348 if (get_application_thread == NULL) {
349 LOG(WARNING) << "Could not get method ID for get application thread";
350 return;
351 }
352
353 jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
354 if (obj == NULL) {
355 LOG(WARNING) << "Could not get application thread";
356 return;
357 }
358
359 application_thread_ = env->NewGlobalRef(obj);
360 }
361
362 if (application_thread_ != NULL && last_process_state_id_ != NULL) {
363 int process_state = env->GetIntField(application_thread_, last_process_state_id_);
364 env->ExceptionClear();
365
366 care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
367 process_state_cares_about_pause_time_.end();
368
369 VLOG(gc) << "New process state " << process_state
370 << " care about pauses " << care_about_pause_times_;
371 }
Mathieu Chartier82353312013-07-18 10:47:51 -0700372}
373
Ian Rogers1d54e732013-05-02 21:10:01 -0700374void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700375 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700376 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700377 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700378 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700379 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700380 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
381 continuous_spaces_.push_back(space);
382 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
383 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700384 }
385
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700386 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700387 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700388
389 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
390 // avoid redundant marking.
391 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700392 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
393 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
394 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700395 if (space->IsImageSpace()) {
396 DCHECK(!seen_zygote);
397 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700398 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700399 DCHECK(!seen_alloc);
400 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700401 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700402 seen_alloc = true;
403 }
404 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800405}
406
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700407void Heap::RegisterGCAllocation(size_t bytes) {
408 if (this != NULL) {
409 gc_memory_overhead_.fetch_add(bytes);
410 }
411}
412
413void Heap::RegisterGCDeAllocation(size_t bytes) {
414 if (this != NULL) {
415 gc_memory_overhead_.fetch_sub(bytes);
416 }
417}
418
Ian Rogers1d54e732013-05-02 21:10:01 -0700419void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
420 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
421 DCHECK(space != NULL);
422 DCHECK(space->GetLiveObjects() != NULL);
423 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
424 DCHECK(space->GetMarkObjects() != NULL);
425 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
426 discontinuous_spaces_.push_back(space);
427}
428
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700429void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700430 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700431 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700432 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800433
434 // Dump cumulative loggers for each GC type.
435 // TODO: C++0x
436 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700437 typedef std::vector<collector::MarkSweep*>::const_iterator It;
438 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800439 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700440 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800441 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800442 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700443 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800444 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700445 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800446 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
447 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
448 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700449 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
450 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
451 << collector->GetName() << " freed: " << freed_objects
452 << " objects with total size " << PrettySize(freed_bytes) << "\n"
453 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
454 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800455 total_duration += total_ns;
456 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700457 }
458 }
459 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700460 size_t total_objects_allocated = GetObjectsAllocatedEver();
461 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700462 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700463 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700464 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
465 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700466 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700467 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700468 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700469 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700470 os << "Total number of allocations: " << total_objects_allocated << "\n";
471 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700472 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700473 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
474 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
475 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700476 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700477 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
478 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700479 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700480}
481
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800482Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700483 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700484 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700485 }
486
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800487 STLDeleteElements(&mark_sweep_collectors_);
488
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700489 // If we don't reset then the mark stack complains in it's destructor.
490 allocation_stack_->Reset();
491 live_stack_->Reset();
492
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800493 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800494 // We can't take the heap lock here because there might be a daemon thread suspended with the
495 // heap lock held. We know though that no non-daemon threads are executing, and we know that
496 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
497 // 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 -0700498 STLDeleteElements(&continuous_spaces_);
499 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700500 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700501 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700502}
503
Ian Rogers1d54e732013-05-02 21:10:01 -0700504space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
505 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700506 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700507 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
508 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700509 if ((*it)->Contains(obj)) {
510 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700511 }
512 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700513 if (!fail_ok) {
514 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
515 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700516 return NULL;
517}
518
Ian Rogers1d54e732013-05-02 21:10:01 -0700519space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
520 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700521 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700522 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
523 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
524 if ((*it)->Contains(obj)) {
525 return *it;
526 }
527 }
528 if (!fail_ok) {
529 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
530 }
531 return NULL;
532}
533
534space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
535 space::Space* result = FindContinuousSpaceFromObject(obj, true);
536 if (result != NULL) {
537 return result;
538 }
539 return FindDiscontinuousSpaceFromObject(obj, true);
540}
541
542space::ImageSpace* Heap::GetImageSpace() const {
543 // TODO: C++0x auto
544 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
545 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700546 if ((*it)->IsImageSpace()) {
547 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700548 }
549 }
550 return NULL;
551}
552
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700553static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700554 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700555 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700556 size_t chunk_free_bytes = chunk_size - used_bytes;
557 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
558 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700559 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700560}
561
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800562mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
563 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700564 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
565 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800566 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700567
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800568 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700569 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700570 uint64_t allocation_start = 0;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700571 if (UNLIKELY(measure_allocation_time_)) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700572 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700573 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700574
575 // We need to have a zygote space or else our newly allocated large object can end up in the
576 // Zygote resulting in it being prematurely freed.
577 // We can only do this for primive objects since large objects will not be within the card table
578 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers333cf1b2013-07-24 11:57:02 -0700579 bool large_object_allocation =
580 byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray();
581 if (UNLIKELY(large_object_allocation)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700582 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700583 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700584 // Make sure that our large object didn't get placed anywhere within the space interval or else
585 // it breaks the immune range.
586 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700587 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
588 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700589 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700590 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700591
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700592 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700593 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700594 size = alloc_space_->AllocationSize(obj);
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 Chartiere0f0cb32012-08-28 11:26:00 -0700602 RecordAllocation(size, 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 Chartier2fde5332012-09-14 14:51:54 -0700607 if (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 }
612 VerifyObject(obj);
613
Ian Rogers333cf1b2013-07-24 11:57:02 -0700614 if (UNLIKELY(measure_allocation_time_)) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700615 total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700616 }
617
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700618 return obj;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700619 } else {
620 std::ostringstream oss;
621 int64_t total_bytes_free = GetFreeMemory();
622 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
623 << " free bytes";
624 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
625 if (!large_object_allocation && total_bytes_free >= byte_count) {
626 size_t max_contiguous_allocation = 0;
627 // TODO: C++0x auto
628 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
629 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
630 space::ContinuousSpace* space = *it;
631 if (space->IsDlMallocSpace()) {
632 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
633 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800634 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700635 oss << "; failed due to fragmentation (largest possible contiguous allocation "
636 << max_contiguous_allocation << " bytes)";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700637 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700638 self->ThrowOutOfMemoryError(oss.str().c_str());
639 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700640 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700641}
642
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800643bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700644 // Note: we deliberately don't take the lock here, and mustn't test anything that would
645 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700646 if (obj == NULL) {
647 return true;
648 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700649 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700650 return false;
651 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700652 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700653}
654
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800655bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700656 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700657 if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700658 return false;
659 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700660 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
661 space::DiscontinuousSpace* d_space = NULL;
662 if (c_space != NULL) {
663 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700664 return true;
665 }
666 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700667 d_space = FindDiscontinuousSpaceFromObject(obj, true);
668 if (d_space != NULL) {
669 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700670 return true;
671 }
672 }
673 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700674 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Ian Rogers1d54e732013-05-02 21:10:01 -0700675 for (size_t i = 0; i < 5; ++i) {
676 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
677 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
678 return true;
679 }
680 NanoSleep(MsToNs(10));
681 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700682 // We need to check the bitmaps again since there is a race where we mark something as live and
683 // then clear the stack containing it.
684 if (c_space != NULL) {
685 if (c_space->GetLiveBitmap()->Test(obj)) {
686 return true;
687 }
688 } else {
689 d_space = FindDiscontinuousSpaceFromObject(obj, true);
690 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
691 return true;
692 }
693 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700694 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700695}
696
Ian Rogers04d7aa92013-03-16 14:29:17 -0700697void Heap::VerifyObjectImpl(const mirror::Object* obj) {
698 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700699 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700700 return;
701 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700702 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700703}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700704
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700705void Heap::DumpSpaces() {
706 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700707 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
708 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
709 space::ContinuousSpace* space = *it;
710 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
711 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700712 LOG(INFO) << space << " " << *space << "\n"
713 << live_bitmap << " " << *live_bitmap << "\n"
714 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700715 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700716 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
717 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
718 space::DiscontinuousSpace* space = *it;
719 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700720 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700721}
722
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800723void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800724 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700725 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700726 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800727 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
728 return;
729 }
730 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
731 mirror::Object::ClassOffset().Int32Value();
732 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
733 if (UNLIKELY(c == NULL)) {
734 LOG(FATAL) << "Null class in object: " << obj;
735 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
736 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
737 }
738 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
739 // Note: we don't use the accessors here as they have internal sanity checks
740 // that we don't want to run
741 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
742 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
743 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
744 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
745 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700746
Ian Rogers62d6c772013-02-27 08:32:07 -0800747 if (verify_object_mode_ != kVerifyAllFast) {
748 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
749 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700750 if (!IsLiveObjectLocked(obj)) {
751 DumpSpaces();
752 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700753 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700754 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700755 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
756 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700757 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700758}
759
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800760void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700761 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700762 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700763}
764
765void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700766 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700767 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700768}
769
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800770void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700771 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700772 DCHECK_GT(size, 0u);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700773 num_bytes_allocated_.fetch_add(size);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700774
775 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700776 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700777 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700778 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700779
780 // TODO: Update these atomically.
781 RuntimeStats* global_stats = Runtime::Current()->GetStats();
782 ++global_stats->allocated_objects;
783 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700784 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700785
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700786 // This is safe to do since the GC will never free objects which are neither in the allocation
787 // stack or the live bitmap.
788 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700789 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700790 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700791}
792
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700793void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700794 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700795 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700796
797 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700798 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700799 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700800 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700801
802 // TODO: Do this concurrently.
803 RuntimeStats* global_stats = Runtime::Current()->GetStats();
804 global_stats->freed_objects += freed_objects;
805 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700806 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700807}
808
Ian Rogers1d54e732013-05-02 21:10:01 -0700809mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
810 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700811 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800812 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
813 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
814 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
815 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700816 return NULL;
817 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700818 }
819
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700820 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700821}
822
Ian Rogers1d54e732013-05-02 21:10:01 -0700823mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700824 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
825 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700826 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700827 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700828
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800829 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700830 if (ptr != NULL) {
831 return ptr;
832 }
833
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700834 // The allocation failed. If the GC is running, block until it completes, and then retry the
835 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700836 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
837 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700838 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700839 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700840 if (ptr != NULL) {
841 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700842 }
843 }
844
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700845 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700846 for (size_t i = static_cast<size_t>(last_gc) + 1;
847 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700848 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700849 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700850 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700851 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700852 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700853 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
854 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700855 break;
856 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700857 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700858 run_gc = have_zygote_space_;
859 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700860 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700861 run_gc = true;
862 break;
863 default:
864 break;
865 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700866
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700867 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700868 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700869 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800870 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700871 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700872
873 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700874 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700875 if (ptr != NULL) {
876 return ptr;
877 }
878 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700879 }
880
881 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700882 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700883 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700884 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700885 return ptr;
886 }
887
Elliott Hughes81ff3182012-03-23 20:35:56 -0700888 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
889 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
890 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700891
Elliott Hughes418dfe72011-10-06 18:56:27 -0700892 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700893 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
894 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700895
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700896 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700897 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700898 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700899}
900
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700901void Heap::SetTargetHeapUtilization(float target) {
902 DCHECK_GT(target, 0.0f); // asserted in Java code
903 DCHECK_LT(target, 1.0f);
904 target_utilization_ = target;
905}
906
Ian Rogers1d54e732013-05-02 21:10:01 -0700907size_t Heap::GetObjectsAllocated() const {
908 size_t total = 0;
909 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
910 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
911 space::ContinuousSpace* space = *it;
912 if (space->IsDlMallocSpace()) {
913 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700914 }
915 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700916 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
917 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
918 space::DiscontinuousSpace* space = *it;
919 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
920 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700921 return total;
922}
923
Ian Rogers1d54e732013-05-02 21:10:01 -0700924size_t Heap::GetObjectsAllocatedEver() const {
925 size_t total = 0;
926 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
927 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
928 space::ContinuousSpace* space = *it;
929 if (space->IsDlMallocSpace()) {
930 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700931 }
932 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700933 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
934 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
935 space::DiscontinuousSpace* space = *it;
936 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
937 }
938 return total;
939}
940
941size_t Heap::GetBytesAllocatedEver() const {
942 size_t total = 0;
943 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
944 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
945 space::ContinuousSpace* space = *it;
946 if (space->IsDlMallocSpace()) {
947 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
948 }
949 }
950 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
951 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
952 space::DiscontinuousSpace* space = *it;
953 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
954 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700955 return total;
956}
957
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700958class InstanceCounter {
959 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800960 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700961 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800962 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700963 }
964
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800965 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800966 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800967 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800968 if (use_is_assignable_from_) {
969 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
970 ++counts_[i];
971 }
972 } else {
973 if (instance_class == classes_[i]) {
974 ++counts_[i];
975 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700976 }
977 }
978 }
979
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700980 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800981 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800982 bool use_is_assignable_from_;
983 uint64_t* const counts_;
984
985 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700986};
987
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800988void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800989 uint64_t* counts) {
990 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
991 // is empty, so the live bitmap is the only place we need to look.
992 Thread* self = Thread::Current();
993 self->TransitionFromRunnableToSuspended(kNative);
994 CollectGarbage(false);
995 self->TransitionFromSuspendedToRunnable();
996
997 InstanceCounter counter(classes, use_is_assignable_from, counts);
998 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700999 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001000}
1001
Elliott Hughes3b78c942013-01-15 17:35:41 -08001002class InstanceCollector {
1003 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001004 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001005 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1006 : class_(c), max_count_(max_count), instances_(instances) {
1007 }
1008
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001009 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1010 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001011 if (instance_class == class_) {
1012 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001013 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001014 }
1015 }
1016 }
1017
1018 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001019 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001020 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001021 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001022
1023 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1024};
1025
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001026void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1027 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001028 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1029 // is empty, so the live bitmap is the only place we need to look.
1030 Thread* self = Thread::Current();
1031 self->TransitionFromRunnableToSuspended(kNative);
1032 CollectGarbage(false);
1033 self->TransitionFromSuspendedToRunnable();
1034
1035 InstanceCollector collector(c, max_count, instances);
1036 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1037 GetLiveBitmap()->Visit(collector);
1038}
1039
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001040class ReferringObjectsFinder {
1041 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001042 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1043 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001044 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1045 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1046 }
1047
1048 // For bitmap Visit.
1049 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1050 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001051 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001052 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001053 }
1054
1055 // For MarkSweep::VisitObjectReferences.
Brian Carlstromdf629502013-07-17 22:39:56 -07001056 void operator()(const mirror::Object* referrer, const mirror::Object* object,
1057 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001058 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001059 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001060 }
1061 }
1062
1063 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001064 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001065 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001066 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001067
1068 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1069};
1070
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001071void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1072 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001073 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1074 // is empty, so the live bitmap is the only place we need to look.
1075 Thread* self = Thread::Current();
1076 self->TransitionFromRunnableToSuspended(kNative);
1077 CollectGarbage(false);
1078 self->TransitionFromSuspendedToRunnable();
1079
1080 ReferringObjectsFinder finder(o, max_count, referring_objects);
1081 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1082 GetLiveBitmap()->Visit(finder);
1083}
1084
Ian Rogers30fab402012-01-23 15:43:46 -08001085void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001086 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1087 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001088 Thread* self = Thread::Current();
1089 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001090 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001091}
1092
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001093void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001094 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001095 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1096 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001097 Thread* self = Thread::Current();
1098 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001099
1100 // Try to see if we have any Zygote spaces.
1101 if (have_zygote_space_) {
1102 return;
1103 }
1104
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001105 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1106
1107 {
1108 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001109 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001110 FlushAllocStack();
1111 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001112
Ian Rogers1d54e732013-05-02 21:10:01 -07001113 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1114 // of the remaining available heap memory.
1115 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001116 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -07001117 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001118
Ian Rogers1d54e732013-05-02 21:10:01 -07001119 // Change the GC retention policy of the zygote space to only collect when full.
1120 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1121 AddContinuousSpace(alloc_space_);
1122 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001123
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001124 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001125 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -07001126 typedef std::vector<collector::MarkSweep*>::const_iterator It;
1127 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1128 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001129 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001130 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001131}
1132
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001133void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001134 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1135 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001136 allocation_stack_->Reset();
1137}
1138
Ian Rogers1d54e732013-05-02 21:10:01 -07001139void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1140 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001141 mirror::Object** limit = stack->End();
1142 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1143 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001144 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001145 if (LIKELY(bitmap->HasAddress(obj))) {
1146 bitmap->Set(obj);
1147 } else {
1148 large_objects->Set(obj);
1149 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001150 }
1151}
1152
Ian Rogers1d54e732013-05-02 21:10:01 -07001153void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1154 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001155 mirror::Object** limit = stack->End();
1156 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1157 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001158 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001159 if (LIKELY(bitmap->HasAddress(obj))) {
1160 bitmap->Clear(obj);
1161 } else {
1162 large_objects->Clear(obj);
1163 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001164 }
1165}
1166
Ian Rogers1d54e732013-05-02 21:10:01 -07001167collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1168 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001169 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001170
1171 switch (gc_cause) {
1172 case kGcCauseForAlloc:
1173 ATRACE_BEGIN("GC (alloc)");
1174 break;
1175 case kGcCauseBackground:
1176 ATRACE_BEGIN("GC (background)");
1177 break;
1178 case kGcCauseExplicit:
1179 ATRACE_BEGIN("GC (explicit)");
1180 break;
1181 }
1182
Mathieu Chartier65db8802012-11-20 12:36:46 -08001183 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001184 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001185
Ian Rogers120f1c72012-09-28 17:17:10 -07001186 if (self->IsHandlingStackOverflow()) {
1187 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1188 }
1189
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001190 // Ensure there is only one GC at a time.
1191 bool start_collect = false;
1192 while (!start_collect) {
1193 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001194 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001195 if (!is_gc_running_) {
1196 is_gc_running_ = true;
1197 start_collect = true;
1198 }
1199 }
1200 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001201 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001202 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1203 // Not doing at the moment to ensure soft references are cleared.
1204 }
1205 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001206 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001207
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001208 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1209 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1210 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1211 }
1212
Ian Rogers1d54e732013-05-02 21:10:01 -07001213 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001214 uint64_t gc_start_size = GetBytesAllocated();
1215 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001216 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001217 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1218 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001219 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001220 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001221 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001222 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1223 }
1224
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001225 if (gc_type == collector::kGcTypeSticky &&
1226 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1227 gc_type = collector::kGcTypePartial;
1228 }
1229
Ian Rogers1d54e732013-05-02 21:10:01 -07001230 DCHECK_LT(gc_type, collector::kGcTypeMax);
1231 DCHECK_NE(gc_type, collector::kGcTypeNone);
1232 collector::MarkSweep* collector = NULL;
1233 typedef std::vector<collector::MarkSweep*>::iterator It;
1234 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1235 it != end; ++it) {
1236 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001237 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1238 collector = cur_collector;
1239 break;
1240 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001241 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001242 CHECK(collector != NULL)
1243 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1244 << " and type=" << gc_type;
1245 collector->clear_soft_references_ = clear_soft_references;
1246 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001247 total_objects_freed_ever_ += collector->GetFreedObjects();
1248 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001249
Ian Rogers1d54e732013-05-02 21:10:01 -07001250 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001251 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1252 bool was_slow = duration > kSlowGcThreshold ||
1253 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1254 for (size_t i = 0; i < pauses.size(); ++i) {
1255 if (pauses[i] > kLongGcPauseThreshold) {
1256 was_slow = true;
1257 }
1258 }
1259
1260 if (was_slow) {
1261 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001262 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001263 const size_t total_memory = GetTotalMemory();
1264 std::ostringstream pause_string;
1265 for (size_t i = 0; i < pauses.size(); ++i) {
1266 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1267 << ((i != pauses.size() - 1) ? ", " : "");
1268 }
1269 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001270 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1271 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1272 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1273 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001274 if (VLOG_IS_ON(heap)) {
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001275 LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001276 }
1277 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001278
Ian Rogers15bf2d32012-08-28 17:33:04 -07001279 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001280 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001281 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001282 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001283 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001284 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001285 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001286
Ian Rogers15bf2d32012-08-28 17:33:04 -07001287 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001288 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001289 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001290 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001291}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001292
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001293void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::TimingLogger& timings,
Ian Rogers1d54e732013-05-02 21:10:01 -07001294 collector::GcType gc_type) {
1295 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001296 // 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 -07001297 // cards.
1298 return;
1299 }
1300
1301 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001302 if (gc_type == collector::kGcTypePartial) {
1303 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001304 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001305
Ian Rogers1d54e732013-05-02 21:10:01 -07001306 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001307 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001308 }
1309
1310 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001311 timings.NewSplit("UpdateModUnionTable");
1312 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001313
1314 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001315 timings.NewSplit("MarkImageToAllocSpaceReferences");
1316 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001317}
1318
Ian Rogers1d54e732013-05-02 21:10:01 -07001319static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001320 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001321 if (root == obj) {
1322 LOG(INFO) << "Object " << obj << " is a root";
1323 }
1324}
1325
1326class ScanVisitor {
1327 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001328 void operator()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001329 LOG(INFO) << "Would have rescanned object " << obj;
1330 }
1331};
1332
Ian Rogers1d54e732013-05-02 21:10:01 -07001333// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001334class VerifyReferenceVisitor {
1335 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001336 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001337 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001338 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001339
1340 bool Failed() const {
1341 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001342 }
1343
1344 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001345 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001346 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1347 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001348 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001349 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001350 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1351 accounting::CardTable* card_table = heap_->GetCardTable();
1352 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1353 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001354
Ian Rogers1d54e732013-05-02 21:10:01 -07001355 if (obj != NULL) {
1356 byte* card_addr = card_table->CardFromAddr(obj);
1357 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1358 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1359 << "\nObj type " << PrettyTypeOf(obj)
1360 << "\nRef type " << PrettyTypeOf(ref);
1361 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1362 void* cover_begin = card_table->AddrFromCard(card_addr);
1363 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1364 accounting::CardTable::kCardSize);
1365 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1366 << "-" << cover_end;
1367 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001368
Ian Rogers1d54e732013-05-02 21:10:01 -07001369 // Print out how the object is live.
1370 if (bitmap != NULL && bitmap->Test(obj)) {
1371 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1372 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001373 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001374 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1375 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001376 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001377 LOG(ERROR) << "Object " << obj << " found in live stack";
1378 }
1379 // Attempt to see if the card table missed the reference.
1380 ScanVisitor scan_visitor;
1381 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1382 card_table->Scan(bitmap, byte_cover_begin,
1383 byte_cover_begin + accounting::CardTable::kCardSize,
1384 scan_visitor, VoidFunctor());
1385
1386 // Search to see if any of the roots reference our object.
1387 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1388 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1389
1390 // Search to see if any of the roots reference our reference.
1391 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1392 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1393 } else {
1394 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001395 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001396 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001397 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001398 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001399 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001400 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001401 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001402 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1403 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1404 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001405 }
1406 }
1407
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001408 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001409 return heap_->IsLiveObjectLocked(obj);
1410 }
1411
1412 static void VerifyRoots(const mirror::Object* root, void* arg) {
1413 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1414 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001415 }
1416
1417 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001418 Heap* const heap_;
1419 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001420};
1421
Ian Rogers1d54e732013-05-02 21:10:01 -07001422// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001423class VerifyObjectVisitor {
1424 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001425 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001426
Brian Carlstromdf629502013-07-17 22:39:56 -07001427 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001428 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001429 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1430 // be live or else how did we find it in the live bitmap?
1431 VerifyReferenceVisitor visitor(heap_);
1432 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1433 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001434 }
1435
1436 bool Failed() const {
1437 return failed_;
1438 }
1439
1440 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001441 Heap* const heap_;
1442 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001443};
1444
1445// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001446bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001447 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001448 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001449 allocation_stack_->Sort();
1450 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001451 // Perform the verification.
1452 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001453 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001454 GetLiveBitmap()->Visit(visitor);
1455 // We don't want to verify the objects in the allocation stack since they themselves may be
1456 // pointing to dead objects if they are not reachable.
1457 if (visitor.Failed()) {
1458 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001459 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001460 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001461 return true;
1462}
1463
1464class VerifyReferenceCardVisitor {
1465 public:
1466 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1467 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1468 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001469 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001470 }
1471
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001472 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1473 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001474 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1475 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001476 // Filter out class references since changing an object's class does not mark the card as dirty.
1477 // Also handles large objects, since the only reference they hold is a class reference.
1478 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001479 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001480 // If the object is not dirty and it is referencing something in the live stack other than
1481 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001482 if (!card_table->AddrIsInCardTable(obj)) {
1483 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1484 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001485 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001486 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1487 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001488 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001489 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1490 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001491 LOG(ERROR) << "Object " << obj << " found in live stack";
1492 }
1493 if (heap_->GetLiveBitmap()->Test(obj)) {
1494 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1495 }
1496 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1497 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1498
1499 // Print which field of the object is dead.
1500 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001501 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001502 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001503 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1504 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001505 CHECK(fields != NULL);
1506 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001507 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001508 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1509 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1510 << PrettyField(cur);
1511 break;
1512 }
1513 }
1514 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001515 const mirror::ObjectArray<mirror::Object>* object_array =
1516 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001517 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1518 if (object_array->Get(i) == ref) {
1519 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1520 }
1521 }
1522 }
1523
1524 *failed_ = true;
1525 }
1526 }
1527 }
1528 }
1529
1530 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001531 Heap* const heap_;
1532 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001533};
1534
1535class VerifyLiveStackReferences {
1536 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001537 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001538 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001539 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001540
Brian Carlstromdf629502013-07-17 22:39:56 -07001541 void operator()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001542 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1543 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001544 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001545 }
1546
1547 bool Failed() const {
1548 return failed_;
1549 }
1550
1551 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001552 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001553 bool failed_;
1554};
1555
1556bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001557 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001558
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001559 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001560 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001561 VerifyLiveStackReferences visitor(this);
1562 GetLiveBitmap()->Visit(visitor);
1563
1564 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001565 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001566 visitor(*it);
1567 }
1568
1569 if (visitor.Failed()) {
1570 DumpSpaces();
1571 return false;
1572 }
1573 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001574}
1575
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001576void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001577 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001578
1579 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001580 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001581 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001582 }
1583}
1584
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001585void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001586 // Clear cards and keep track of cards cleared in the mod-union table.
1587 typedef std::vector<space::ContinuousSpace*>::iterator It;
1588 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1589 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001590 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001591 timings.NewSplit("ModUnionClearCards");
1592 image_mod_union_table_->ClearCards(space);
1593 } else if (space->IsZygoteSpace()) {
1594 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001595 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001596 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001597 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1598 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001599 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001600 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001601 }
1602 }
1603}
1604
Ian Rogers1d54e732013-05-02 21:10:01 -07001605void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001606 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1607 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001608
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001609 if (verify_pre_gc_heap_) {
1610 thread_list->SuspendAll();
1611 {
1612 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1613 if (!VerifyHeapReferences()) {
1614 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1615 }
1616 }
1617 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001618 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001619
1620 // Check that all objects which reference things in the live stack are on dirty cards.
1621 if (verify_missing_card_marks_) {
1622 thread_list->SuspendAll();
1623 {
1624 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1625 SwapStacks();
1626 // Sort the live stack so that we can quickly binary search it later.
1627 if (!VerifyMissingCardMarks()) {
1628 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1629 }
1630 SwapStacks();
1631 }
1632 thread_list->ResumeAll();
1633 }
1634
1635 if (verify_mod_union_table_) {
1636 thread_list->SuspendAll();
1637 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1638 zygote_mod_union_table_->Update();
1639 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001640 image_mod_union_table_->Update();
1641 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001642 thread_list->ResumeAll();
1643 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001644}
1645
Ian Rogers1d54e732013-05-02 21:10:01 -07001646void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001647 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001648
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001649 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1650 // reachable objects.
1651 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001652 Thread* self = Thread::Current();
1653 CHECK_NE(self->GetState(), kRunnable);
1654 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001655 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001656 {
1657 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1658 // Swapping bound bitmaps does nothing.
1659 gc->SwapBitmaps();
1660 if (!VerifyHeapReferences()) {
1661 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1662 }
1663 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001664 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001665 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001666 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001667 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001668}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001669
Ian Rogers1d54e732013-05-02 21:10:01 -07001670void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001671 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001672
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001673 if (verify_system_weaks_) {
1674 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001675 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001676 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001677 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001678}
1679
Ian Rogers1d54e732013-05-02 21:10:01 -07001680collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1681 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001682 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001683 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001684 bool do_wait;
1685 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001686 {
1687 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001688 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001689 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001690 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001691 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001692 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001693 // We must wait, change thread state then sleep on gc_complete_cond_;
1694 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1695 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001696 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001697 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001698 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001699 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001700 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001701 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001702 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001703 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001704 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001705 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1706 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001707 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001708 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001709 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001710 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001711}
1712
Elliott Hughesc967f782012-04-16 10:23:15 -07001713void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001714 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001715 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001716 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001717}
1718
1719size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001720 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001721}
1722
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001723void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001724 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001725 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001726 << PrettySize(GetMaxMemory());
1727 max_allowed_footprint = GetMaxMemory();
1728 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001729 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001730}
1731
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001732void Heap::UpdateMaxNativeFootprint() {
1733 size_t native_size = native_bytes_allocated_;
1734 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1735 size_t target_size = native_size / GetTargetHeapUtilization();
1736 if (target_size > native_size + max_free_) {
1737 target_size = native_size + max_free_;
1738 } else if (target_size < native_size + min_free_) {
1739 target_size = native_size + min_free_;
1740 }
1741 native_footprint_gc_watermark_ = target_size;
1742 native_footprint_limit_ = 2 * target_size - native_size;
1743}
1744
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001745void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001746 // We know what our utilization is at this moment.
1747 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001748 const size_t bytes_allocated = GetBytesAllocated();
1749 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001750 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001751
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001752 size_t target_size;
1753 if (gc_type != collector::kGcTypeSticky) {
1754 // Grow the heap for non sticky GC.
1755 target_size = bytes_allocated / GetTargetHeapUtilization();
1756 if (target_size > bytes_allocated + max_free_) {
1757 target_size = bytes_allocated + max_free_;
1758 } else if (target_size < bytes_allocated + min_free_) {
1759 target_size = bytes_allocated + min_free_;
1760 }
1761 next_gc_type_ = collector::kGcTypeSticky;
1762 } else {
1763 // Based on how close the current heap size is to the target size, decide
1764 // whether or not to do a partial or sticky GC next.
1765 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1766 next_gc_type_ = collector::kGcTypeSticky;
1767 } else {
1768 next_gc_type_ = collector::kGcTypePartial;
1769 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001770
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001771 // If we have freed enough memory, shrink the heap back down.
1772 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1773 target_size = bytes_allocated + max_free_;
1774 } else {
1775 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1776 }
1777 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001778 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001779
Ian Rogers1d54e732013-05-02 21:10:01 -07001780 // Calculate when to perform the next ConcurrentGC.
1781 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001782 // Calculate the estimated GC duration.
1783 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1784 // Estimate how many remaining bytes we will have when we need to start the next GC.
1785 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001786 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1787 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1788 // A never going to happen situation that from the estimated allocation rate we will exceed
1789 // the applications entire footprint with the given estimated allocation rate. Schedule
1790 // another GC straight away.
1791 concurrent_start_bytes_ = bytes_allocated;
1792 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001793 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1794 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1795 // right away.
1796 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001797 }
1798 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1799 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1800 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001801
1802 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001803}
1804
jeffhaoc1160702011-10-27 15:48:45 -07001805void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001806 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001807 alloc_space_->ClearGrowthLimit();
1808}
1809
Elliott Hughesadb460d2011-10-05 17:02:34 -07001810void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001811 MemberOffset reference_queue_offset,
1812 MemberOffset reference_queueNext_offset,
1813 MemberOffset reference_pendingNext_offset,
1814 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001815 reference_referent_offset_ = reference_referent_offset;
1816 reference_queue_offset_ = reference_queue_offset;
1817 reference_queueNext_offset_ = reference_queueNext_offset;
1818 reference_pendingNext_offset_ = reference_pendingNext_offset;
1819 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1820 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1821 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1822 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1823 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1824 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1825}
1826
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001827mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001828 DCHECK(reference != NULL);
1829 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001830 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001831}
1832
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001833void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001834 DCHECK(reference != NULL);
1835 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1836 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1837}
1838
1839// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001840bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001841 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001842 const mirror::Object* queue =
1843 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1844 const mirror::Object* queue_next =
1845 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001846 return (queue != NULL) && (queue_next == NULL);
1847}
1848
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001849void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001850 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001851 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1852 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001853 EnqueuePendingReference(ref, cleared_reference_list);
1854}
1855
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001856void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001857 DCHECK(ref != NULL);
1858 DCHECK(list != NULL);
1859
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001860 // TODO: Remove this lock, use atomic stacks for storing references.
1861 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001862 if (*list == NULL) {
1863 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1864 *list = ref;
1865 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001866 mirror::Object* head =
1867 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001868 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1869 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1870 }
1871}
1872
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001873mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001874 DCHECK(list != NULL);
1875 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001876 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1877 false);
1878 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001879
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001880 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1881 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001882 if (*list == head) {
1883 ref = *list;
1884 *list = NULL;
1885 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001886 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1887 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001888 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1889 ref = head;
1890 }
1891 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1892 return ref;
1893}
1894
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001895void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001896 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001897 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001898 ArgArray arg_array(NULL, 0);
1899 arg_array.Append(reinterpret_cast<uint32_t>(object));
1900 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001901 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001902}
1903
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001904void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001905 DCHECK(cleared != NULL);
1906 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001907 // When a runtime isn't started there are no reference queues to care about so ignore.
1908 if (LIKELY(Runtime::Current()->IsStarted())) {
1909 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001910 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001911 ArgArray arg_array(NULL, 0);
1912 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1913 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001914 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001915 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001916 *cleared = NULL;
1917 }
1918}
1919
Ian Rogers1f539342012-10-03 21:09:42 -07001920void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001921 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001922 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001923 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001924 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001925 !runtime->IsConcurrentGcEnabled()) {
1926 return;
1927 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001928 {
1929 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1930 if (runtime->IsShuttingDown()) {
1931 return;
1932 }
1933 }
1934 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001935 return;
1936 }
1937
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001938 // We already have a request pending, no reason to start more until we update
1939 // concurrent_start_bytes_.
1940 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1941
Ian Rogers120f1c72012-09-28 17:17:10 -07001942 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001943 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1944 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001945 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1946 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001947 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001948}
1949
Ian Rogers81d425b2012-09-27 16:03:43 -07001950void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001951 {
1952 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001953 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001954 return;
1955 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001956 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001957
Mathieu Chartier65db8802012-11-20 12:36:46 -08001958 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001959 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001960 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001961 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001962}
1963
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001964void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001965 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1966 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1967 // a space it will hold its lock and can become a cause of jank.
1968 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1969 // forking.
1970
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001971 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1972 // because that only marks object heads, so a large array looks like lots of empty space. We
1973 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1974 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1975 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1976 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001977 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001978 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001979 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
Mathieu Chartiere0a53e92013-08-05 10:17:40 -07001980 if ((utilization > 0.75f && !IsLowMemoryMode()) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
1981 // Don't bother trimming the alloc space if it's more than 75% utilized and low memory mode is
1982 // not enabled, or if a heap trim occurred in the last two seconds.
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001983 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001984 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001985
1986 Thread* self = Thread::Current();
1987 {
1988 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1989 Runtime* runtime = Runtime::Current();
1990 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1991 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1992 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1993 // as we don't hold the lock while requesting the trim).
1994 return;
1995 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001996 }
Ian Rogers48931882013-01-22 14:35:16 -08001997
Ian Rogers1d54e732013-05-02 21:10:01 -07001998 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07001999 ListenForProcessStateChange();
2000
2001 // Trim only if we do not currently care about pause times.
2002 if (!care_about_pause_times_) {
2003 JNIEnv* env = self->GetJniEnv();
2004 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2005 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2006 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2007 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2008 CHECK(!env->ExceptionCheck());
2009 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002010}
2011
Ian Rogers48931882013-01-22 14:35:16 -08002012size_t Heap::Trim() {
2013 // Handle a requested heap trim on a thread outside of the main GC thread.
2014 return alloc_space_->Trim();
2015}
2016
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002017bool Heap::IsGCRequestPending() const {
2018 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2019}
2020
2021void Heap::RegisterNativeAllocation(int bytes) {
2022 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002023 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002024 Thread* self = Thread::Current();
2025 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
2026 // The second watermark is higher than the gc watermark. If you hit this it means you are
2027 // allocating native objects faster than the GC can keep up with.
2028 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2029 JNIEnv* env = self->GetJniEnv();
2030 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
2031 // point.
2032 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
2033 DCHECK(WellKnownClasses::java_lang_System != NULL);
2034 WellKnownClasses::java_lang_System_runFinalization =
2035 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2036 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
2037 }
2038 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
2039 // Just finished a GC, attempt to run finalizers.
2040 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2041 WellKnownClasses::java_lang_System_runFinalization);
2042 CHECK(!env->ExceptionCheck());
2043 }
2044
2045 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2046 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2047 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
2048 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2049 WellKnownClasses::java_lang_System_runFinalization);
2050 CHECK(!env->ExceptionCheck());
2051 }
2052 // We have just run finalizers, update the native watermark since it is very likely that
2053 // finalizers released native managed allocations.
2054 UpdateMaxNativeFootprint();
2055 } else {
2056 if (!IsGCRequestPending()) {
2057 RequestConcurrentGC(self);
2058 }
2059 }
2060 }
2061}
2062
2063void Heap::RegisterNativeFree(int bytes) {
2064 int expected_size, new_size;
2065 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002066 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002067 new_size = expected_size - bytes;
2068 if (new_size < 0) {
2069 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
2070 bytes, expected_size);
2071 break;
2072 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002073 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002074}
2075
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002076int64_t Heap::GetTotalMemory() const {
2077 int64_t ret = 0;
2078 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
2079 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
2080 space::ContinuousSpace* space = *it;
2081 if (space->IsImageSpace()) {
2082 // Currently don't include the image space.
2083 } else if (space->IsDlMallocSpace()) {
2084 // Zygote or alloc space
2085 ret += space->AsDlMallocSpace()->GetFootprint();
2086 }
2087 }
2088 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
2089 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
2090 space::DiscontinuousSpace* space = *it;
2091 if (space->IsLargeObjectSpace()) {
2092 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2093 }
2094 }
2095 return ret;
2096}
2097
Ian Rogers1d54e732013-05-02 21:10:01 -07002098} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002099} // namespace art