blob: e89dd66894ee2a1152d5f745e351312709e50e7b [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070018
Mathieu Chartier752a0e62013-06-27 11:03:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <cutils/trace.h>
Brian Carlstrom5643b782012-02-05 12:32:53 -080021
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070023#include <vector>
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070024#include <valgrind.h>
Carl Shapiro58551df2011-07-24 03:09:51 -070025
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070027#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080028#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070029#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070030#include "gc/accounting/atomic_stack.h"
31#include "gc/accounting/card_table-inl.h"
32#include "gc/accounting/heap_bitmap-inl.h"
33#include "gc/accounting/mod_union_table-inl.h"
34#include "gc/accounting/space_bitmap-inl.h"
35#include "gc/collector/mark_sweep-inl.h"
36#include "gc/collector/partial_mark_sweep.h"
37#include "gc/collector/sticky_mark_sweep.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070038#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/space/image_space.h"
40#include "gc/space/large_object_space.h"
41#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070042#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080043#include "invoke_arg_array_builder.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070044#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/object.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080049#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080050#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070051#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070052#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070053#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070054#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070055#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070056#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070057
58namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070059namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070060
Ian Rogers1d54e732013-05-02 21:10:01 -070061// When to create a log message about a slow GC, 100ms.
Mathieu Chartier720ef762013-08-17 14:46:54 -070062static constexpr uint64_t kSlowGcThreshold = MsToNs(100);
Mathieu Chartier82353312013-07-18 10:47:51 -070063// When to create a log message about a long pause, 5ms.
Mathieu Chartier720ef762013-08-17 14:46:54 -070064static constexpr uint64_t kLongGcPauseThreshold = MsToNs(5);
65static constexpr bool kGCALotMode = false;
66static constexpr size_t kGcAlotInterval = KB;
67static constexpr bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070068// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070069static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070070// If true, measure the total allocation time.
Mathieu Chartier720ef762013-08-17 14:46:54 -070071static constexpr bool kMeasureAllocationTime = false;
Mathieu Chartier0051be62012-10-12 17:47:11 -070072
Mathieu Chartier0051be62012-10-12 17:47:11 -070073Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070074 double target_utilization, size_t capacity, const std::string& original_image_file_name,
75 bool concurrent_gc, size_t num_gc_threads, bool low_memory_mode)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070076 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080077 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070078 concurrent_gc_(concurrent_gc),
Mathieu Chartier63a54342013-07-23 13:17:59 -070079 num_gc_threads_(num_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070080 low_memory_mode_(low_memory_mode),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070081 have_zygote_space_(false),
Mathieu Chartier94c32c52013-08-09 11:14:04 -070082 soft_ref_queue_lock_(NULL),
83 weak_ref_queue_lock_(NULL),
84 finalizer_ref_queue_lock_(NULL),
85 phantom_ref_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080086 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070087 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070088 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080089 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070090 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070091 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070092 native_footprint_gc_watermark_(initial_size),
93 native_footprint_limit_(2 * initial_size),
Mathieu Chartierc39e3422013-08-07 16:41:36 -070094 activity_thread_class_(NULL),
95 application_thread_class_(NULL),
96 activity_thread_(NULL),
97 application_thread_(NULL),
98 last_process_state_id_(NULL),
99 // Initially care about pauses in case we never get notified of process states, or if the JNI
100 // code becomes broken.
101 care_about_pause_times_(true),
Mathieu Chartier720ef762013-08-17 14:46:54 -0700102 concurrent_start_bytes_(concurrent_gc_ ? initial_size - kMinConcurrentRemainingBytes
103 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700104 total_bytes_freed_ever_(0),
105 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700106 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800107 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700108 native_bytes_allocated_(0),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700109 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700110 verify_missing_card_marks_(false),
111 verify_system_weaks_(false),
112 verify_pre_gc_heap_(false),
113 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700114 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700115 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700116 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700117 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800118 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700119 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
120 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
121 * verification is enabled, we limit the size of allocation stacks to speed up their
122 * searching.
123 */
124 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
125 : (kDesiredHeapVerification > kNoHeapVerification) ? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800126 reference_referent_offset_(0),
127 reference_queue_offset_(0),
128 reference_queueNext_offset_(0),
129 reference_pendingNext_offset_(0),
130 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700131 min_free_(min_free),
132 max_free_(max_free),
133 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700134 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700135 total_allocation_time_(0),
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700136 verify_object_mode_(kHeapVerificationNotPermitted),
137 running_on_valgrind_(RUNNING_ON_VALGRIND) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800138 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800139 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700140 }
141
Ian Rogers1d54e732013-05-02 21:10:01 -0700142 live_bitmap_.reset(new accounting::HeapBitmap(this));
143 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700144
Ian Rogers30fab402012-01-23 15:43:46 -0800145 // Requested begin for the alloc space, to follow the mapped image and oat files
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700146 byte* requested_alloc_space_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800147 std::string image_file_name(original_image_file_name);
148 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700149 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
150 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700151 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800152 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
153 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800154 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
155 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700156 if (oat_file_end_addr > requested_alloc_space_begin) {
157 requested_alloc_space_begin =
158 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
159 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700160 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700161 }
162
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700163 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700164 initial_size,
165 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700166 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700167 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700168 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700169 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700170
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700171 // Allocate the large object space.
172 const bool kUseFreeListSpaceForLOS = false;
173 if (kUseFreeListSpaceForLOS) {
174 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
175 } else {
176 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
177 }
178 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
179 AddDiscontinuousSpace(large_object_space_);
180
Ian Rogers1d54e732013-05-02 21:10:01 -0700181 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
182 byte* heap_begin = continuous_spaces_.front()->Begin();
183 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
184 if (continuous_spaces_.back()->IsDlMallocSpace()) {
185 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700186 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700187
Mathieu Chartier02e25112013-08-14 16:14:24 -0700188 // Mark image objects in the live bitmap.
189 for (const auto& space : continuous_spaces_) {
Ian Rogers30fab402012-01-23 15:43:46 -0800190 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700191 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700192 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800193 }
194 }
195
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800196 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700197 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700198 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700199
Mathieu Chartier161a8e02013-08-01 19:12:52 -0700200 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
Ian Rogers1d54e732013-05-02 21:10:01 -0700201 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700202
Ian Rogers1d54e732013-05-02 21:10:01 -0700203 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700204 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700205
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700206 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700207 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700208
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800209 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700210 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700211 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
212 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
213 max_allocation_stack_size_));
214 live_stack_.reset(accounting::ObjectStack::Create("live stack",
215 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700216
Mathieu Chartier65db8802012-11-20 12:36:46 -0800217 // It's still too early to take a lock because there are no threads yet, but we can create locks
218 // now. We don't create it earlier to make it clear that you can't use locks during heap
219 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700220 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700221 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
222 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700223
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700224 // Create the reference queue locks, this is required so for parallel object scanning in the GC.
225 soft_ref_queue_lock_ = new Mutex("Soft reference queue lock");
226 weak_ref_queue_lock_ = new Mutex("Weak reference queue lock");
227 finalizer_ref_queue_lock_ = new Mutex("Finalizer reference queue lock");
228 phantom_ref_queue_lock_ = new Mutex("Phantom reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700229
Ian Rogers1d54e732013-05-02 21:10:01 -0700230 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800231 last_gc_size_ = GetBytesAllocated();
232
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800233 // Create our garbage collectors.
234 for (size_t i = 0; i < 2; ++i) {
235 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700236 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
237 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
238 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700239 }
240
Brian Carlstrom42748892013-07-18 18:04:08 -0700241 CHECK_NE(max_allowed_footprint_, 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800242 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800243 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700244 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700245}
246
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700247void Heap::CreateThreadPool() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700248 if (num_gc_threads_ != 0) {
249 thread_pool_.reset(new ThreadPool(num_gc_threads_));
250 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700251}
252
253void Heap::DeleteThreadPool() {
254 thread_pool_.reset(NULL);
255}
256
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700257static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
258 CHECK(out_value != NULL);
259 jfieldID field = env->GetStaticFieldID(clz, name, "I");
260 if (field == NULL) {
261 env->ExceptionClear();
262 return false;
263 }
264 *out_value = env->GetStaticIntField(clz, field);
265 return true;
266}
267
268void Heap::ListenForProcessStateChange() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700269 VLOG(heap) << "Heap notified of process state change";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700270
271 Thread* self = Thread::Current();
272 JNIEnvExt* env = self->GetJniEnv();
273
274 if (!have_zygote_space_) {
275 return;
276 }
277
278 if (activity_thread_class_ == NULL) {
279 jclass clz = env->FindClass("android/app/ActivityThread");
280 if (clz == NULL) {
281 env->ExceptionClear();
282 LOG(WARNING) << "Could not find activity thread class in process state change";
283 return;
284 }
285 activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
286 }
287
288 if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
289 jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
290 "currentActivityThread",
291 "()Landroid/app/ActivityThread;");
292 if (current_activity_method == NULL) {
293 env->ExceptionClear();
294 LOG(WARNING) << "Could not get method for currentActivityThread";
295 return;
296 }
297
298 jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
299 if (obj == NULL) {
300 env->ExceptionClear();
301 LOG(WARNING) << "Could not get current activity";
302 return;
303 }
304 activity_thread_ = env->NewGlobalRef(obj);
305 }
306
307 if (process_state_cares_about_pause_time_.empty()) {
308 // Just attempt to do this the first time.
309 jclass clz = env->FindClass("android/app/ActivityManager");
310 if (clz == NULL) {
311 LOG(WARNING) << "Activity manager class is null";
312 return;
313 }
314 ScopedLocalRef<jclass> activity_manager(env, clz);
315 std::vector<const char*> care_about_pauses;
316 care_about_pauses.push_back("PROCESS_STATE_TOP");
317 care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
318 // Attempt to read the constants and classify them as whether or not we care about pause times.
319 for (size_t i = 0; i < care_about_pauses.size(); ++i) {
320 int process_state = 0;
321 if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
322 process_state_cares_about_pause_time_.insert(process_state);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700323 VLOG(heap) << "Adding process state " << process_state
324 << " to set of states which care about pause time";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700325 }
326 }
327 }
328
329 if (application_thread_class_ == NULL) {
330 jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
331 if (clz == NULL) {
332 env->ExceptionClear();
333 LOG(WARNING) << "Could not get application thread class";
334 return;
335 }
336 application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
337 last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
338 if (last_process_state_id_ == NULL) {
339 env->ExceptionClear();
340 LOG(WARNING) << "Could not get last process state member";
341 return;
342 }
343 }
344
345 if (application_thread_class_ != NULL && application_thread_ == NULL) {
346 jmethodID get_application_thread =
347 env->GetMethodID(activity_thread_class_, "getApplicationThread",
348 "()Landroid/app/ActivityThread$ApplicationThread;");
349 if (get_application_thread == NULL) {
350 LOG(WARNING) << "Could not get method ID for get application thread";
351 return;
352 }
353
354 jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
355 if (obj == NULL) {
356 LOG(WARNING) << "Could not get application thread";
357 return;
358 }
359
360 application_thread_ = env->NewGlobalRef(obj);
361 }
362
363 if (application_thread_ != NULL && last_process_state_id_ != NULL) {
364 int process_state = env->GetIntField(application_thread_, last_process_state_id_);
365 env->ExceptionClear();
366
367 care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
368 process_state_cares_about_pause_time_.end();
369
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700370 VLOG(heap) << "New process state " << process_state
371 << " care about pauses " << care_about_pause_times_;
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700372 }
Mathieu Chartier82353312013-07-18 10:47:51 -0700373}
374
Ian Rogers1d54e732013-05-02 21:10:01 -0700375void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700376 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700377 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700378 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700379 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700380 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700381 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
382 continuous_spaces_.push_back(space);
383 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
384 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700385 }
386
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700387 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700388 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
389 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
390 return a->Begin() < b->Begin();
391 });
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700392
393 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
394 // avoid redundant marking.
395 bool seen_zygote = false, seen_alloc = false;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700396 for (const auto& space : continuous_spaces_) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700397 if (space->IsImageSpace()) {
398 DCHECK(!seen_zygote);
399 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700400 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700401 DCHECK(!seen_alloc);
402 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700403 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700404 seen_alloc = true;
405 }
406 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800407}
408
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700409void Heap::RegisterGCAllocation(size_t bytes) {
410 if (this != NULL) {
411 gc_memory_overhead_.fetch_add(bytes);
412 }
413}
414
415void Heap::RegisterGCDeAllocation(size_t bytes) {
416 if (this != NULL) {
417 gc_memory_overhead_.fetch_sub(bytes);
418 }
419}
420
Ian Rogers1d54e732013-05-02 21:10:01 -0700421void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
422 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
423 DCHECK(space != NULL);
424 DCHECK(space->GetLiveObjects() != NULL);
425 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
426 DCHECK(space->GetMarkObjects() != NULL);
427 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
428 discontinuous_spaces_.push_back(space);
429}
430
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700431void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700432 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700433 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700434 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800435
436 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800437 uint64_t total_paused_time = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700438 for (const auto& collector : mark_sweep_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800439 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800440 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700441 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800442 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700443 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800444 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
445 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
446 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700447 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
448 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
449 << collector->GetName() << " freed: " << freed_objects
450 << " objects with total size " << PrettySize(freed_bytes) << "\n"
451 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
452 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800453 total_duration += total_ns;
454 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700455 }
456 }
457 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700458 size_t total_objects_allocated = GetObjectsAllocatedEver();
459 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700460 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700461 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700462 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
463 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700464 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700465 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700466 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700467 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700468 os << "Total number of allocations: " << total_objects_allocated << "\n";
469 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700470 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700471 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
472 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
473 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700474 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700475 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
476 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700477 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700478}
479
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800480Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700481 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700482 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700483 }
484
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800485 STLDeleteElements(&mark_sweep_collectors_);
486
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700487 // If we don't reset then the mark stack complains in it's destructor.
488 allocation_stack_->Reset();
489 live_stack_->Reset();
490
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800491 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800492 // We can't take the heap lock here because there might be a daemon thread suspended with the
493 // heap lock held. We know though that no non-daemon threads are executing, and we know that
494 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
495 // 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 -0700496 STLDeleteElements(&continuous_spaces_);
497 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498 delete gc_complete_lock_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700499 delete soft_ref_queue_lock_;
500 delete weak_ref_queue_lock_;
501 delete finalizer_ref_queue_lock_;
502 delete phantom_ref_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700503}
504
Ian Rogers1d54e732013-05-02 21:10:01 -0700505space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
506 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700507 for (const auto& space : continuous_spaces_) {
508 if (space->Contains(obj)) {
509 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700510 }
511 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700512 if (!fail_ok) {
513 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
514 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700515 return NULL;
516}
517
Ian Rogers1d54e732013-05-02 21:10:01 -0700518space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
519 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700520 for (const auto& space : discontinuous_spaces_) {
521 if (space->Contains(obj)) {
522 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700523 }
524 }
525 if (!fail_ok) {
526 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
527 }
528 return NULL;
529}
530
531space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
532 space::Space* result = FindContinuousSpaceFromObject(obj, true);
533 if (result != NULL) {
534 return result;
535 }
536 return FindDiscontinuousSpaceFromObject(obj, true);
537}
538
539space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700540 for (const auto& space : continuous_spaces_) {
541 if (space->IsImageSpace()) {
542 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700543 }
544 }
545 return NULL;
546}
547
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700548static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700549 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700550 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700551 size_t chunk_free_bytes = chunk_size - used_bytes;
552 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
553 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700554 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700555}
556
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800557mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
558 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700559 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
560 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800561 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700562
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800563 mirror::Object* obj = NULL;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700564 size_t bytes_allocated = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700565 uint64_t allocation_start = 0;
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700566 if (UNLIKELY(kMeasureAllocationTime)) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700567 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700568 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700569
570 // We need to have a zygote space or else our newly allocated large object can end up in the
571 // Zygote resulting in it being prematurely freed.
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700572 // We can only do this for primitive objects since large objects will not be within the card table
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700573 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers333cf1b2013-07-24 11:57:02 -0700574 bool large_object_allocation =
575 byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray();
576 if (UNLIKELY(large_object_allocation)) {
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700577 obj = Allocate(self, large_object_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700578 // Make sure that our large object didn't get placed anywhere within the space interval or else
579 // it breaks the immune range.
580 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700581 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
582 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700583 } else {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700584 obj = Allocate(self, alloc_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700585 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700586 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700587 }
588
Mathieu Chartier037813d2012-08-23 16:44:59 -0700589 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700590 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700591
592 // Record allocation after since we want to use the atomic add for the atomic fence to guard
593 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700594 RecordAllocation(bytes_allocated, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700595
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700596 if (Dbg::IsAllocTrackingEnabled()) {
597 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700598 }
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700599 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700600 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800601 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700602 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700603 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700604 if (kDesiredHeapVerification > kNoHeapVerification) {
605 VerifyObject(obj);
606 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700607
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700608 if (UNLIKELY(kMeasureAllocationTime)) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700609 total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700610 }
611
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700612 return obj;
Ian Rogers333cf1b2013-07-24 11:57:02 -0700613 } else {
614 std::ostringstream oss;
615 int64_t total_bytes_free = GetFreeMemory();
616 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
617 << " free bytes";
618 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
619 if (!large_object_allocation && total_bytes_free >= byte_count) {
620 size_t max_contiguous_allocation = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700621 for (const auto& space : continuous_spaces_) {
Ian Rogers333cf1b2013-07-24 11:57:02 -0700622 if (space->IsDlMallocSpace()) {
623 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
624 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800625 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700626 oss << "; failed due to fragmentation (largest possible contiguous allocation "
627 << max_contiguous_allocation << " bytes)";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700628 }
Ian Rogers333cf1b2013-07-24 11:57:02 -0700629 self->ThrowOutOfMemoryError(oss.str().c_str());
630 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700631 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700632}
633
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800634bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700635 // Note: we deliberately don't take the lock here, and mustn't test anything that would
636 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700637 if (obj == NULL) {
638 return true;
639 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700640 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700641 return false;
642 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700643 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700644}
645
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800646bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700647 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700648 if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700649 return false;
650 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700651 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
652 space::DiscontinuousSpace* d_space = NULL;
653 if (c_space != NULL) {
654 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700655 return true;
656 }
657 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700658 d_space = FindDiscontinuousSpaceFromObject(obj, true);
659 if (d_space != NULL) {
660 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700661 return true;
662 }
663 }
664 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700665 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Ian Rogers1d54e732013-05-02 21:10:01 -0700666 for (size_t i = 0; i < 5; ++i) {
667 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
668 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
669 return true;
670 }
671 NanoSleep(MsToNs(10));
672 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700673 // We need to check the bitmaps again since there is a race where we mark something as live and
674 // then clear the stack containing it.
675 if (c_space != NULL) {
676 if (c_space->GetLiveBitmap()->Test(obj)) {
677 return true;
678 }
679 } else {
680 d_space = FindDiscontinuousSpaceFromObject(obj, true);
681 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
682 return true;
683 }
684 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700685 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700686}
687
Ian Rogers04d7aa92013-03-16 14:29:17 -0700688void Heap::VerifyObjectImpl(const mirror::Object* obj) {
689 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700690 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700691 return;
692 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700693 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700694}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700695
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700696void Heap::DumpSpaces() {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700697 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700698 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
699 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700700 LOG(INFO) << space << " " << *space << "\n"
701 << live_bitmap << " " << *live_bitmap << "\n"
702 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700703 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700704 for (const auto& space : discontinuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700705 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700706 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700707}
708
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800709void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800710 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700711 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700712 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800713 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
714 return;
715 }
716 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
717 mirror::Object::ClassOffset().Int32Value();
718 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
719 if (UNLIKELY(c == NULL)) {
720 LOG(FATAL) << "Null class in object: " << obj;
721 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
722 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
723 }
724 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
725 // Note: we don't use the accessors here as they have internal sanity checks
726 // that we don't want to run
727 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
728 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
729 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
730 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
731 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700732
Ian Rogers62d6c772013-02-27 08:32:07 -0800733 if (verify_object_mode_ != kVerifyAllFast) {
734 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
735 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700736 if (!IsLiveObjectLocked(obj)) {
737 DumpSpaces();
738 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700739 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700740 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700741 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
742 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700743 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700744}
745
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800746void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700747 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700748 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700749}
750
751void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700752 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700753 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700754}
755
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700756inline void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700757 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700758 DCHECK_GT(size, 0u);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700759 num_bytes_allocated_.fetch_add(size);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700760
761 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700762 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700763 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700764 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700765
766 // TODO: Update these atomically.
767 RuntimeStats* global_stats = Runtime::Current()->GetStats();
768 ++global_stats->allocated_objects;
769 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700770 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700771
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700772 // This is safe to do since the GC will never free objects which are neither in the allocation
773 // stack or the live bitmap.
774 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700775 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700776 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700777}
778
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700779void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700780 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700781 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700782
783 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700784 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700785 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700786 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700787
788 // TODO: Do this concurrently.
789 RuntimeStats* global_stats = Runtime::Current()->GetStats();
790 global_stats->freed_objects += freed_objects;
791 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700792 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700793}
794
Mathieu Chartier720ef762013-08-17 14:46:54 -0700795inline bool Heap::IsOutOfMemoryOnAllocation(size_t alloc_size, bool grow) {
796 size_t new_footprint = num_bytes_allocated_ + alloc_size;
797 if (UNLIKELY(new_footprint > max_allowed_footprint_)) {
798 if (UNLIKELY(new_footprint > growth_limit_)) {
799 return true;
800 }
801 if (!concurrent_gc_) {
802 if (!grow) {
803 return true;
804 } else {
805 max_allowed_footprint_ = new_footprint;
806 }
807 }
808 }
809 return false;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700810}
811
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700812inline mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
813 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700814 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700815 return NULL;
816 }
817 return space->Alloc(self, alloc_size, bytes_allocated);
818}
819
820// DlMallocSpace-specific version.
821inline mirror::Object* Heap::TryToAllocate(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
822 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700823 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700824 return NULL;
825 }
Mathieu Chartier720ef762013-08-17 14:46:54 -0700826 if (LIKELY(!running_on_valgrind_)) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700827 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
828 } else {
829 return space->Alloc(self, alloc_size, bytes_allocated);
830 }
831}
832
833template <class T>
Mathieu Chartier720ef762013-08-17 14:46:54 -0700834inline mirror::Object* Heap::Allocate(Thread* self, T* space, size_t alloc_size,
835 size_t* bytes_allocated) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700836 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
837 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700838 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700839 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700840
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700841 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700842 if (ptr != NULL) {
843 return ptr;
844 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700845 return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
846}
847
Mathieu Chartier720ef762013-08-17 14:46:54 -0700848mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space,
849 size_t alloc_size, size_t* bytes_allocated) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700850 mirror::Object* ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700851
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700852 // The allocation failed. If the GC is running, block until it completes, and then retry the
853 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700854 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
855 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700856 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700857 ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700858 if (ptr != NULL) {
859 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700860 }
861 }
862
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700863 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700864 for (size_t i = static_cast<size_t>(last_gc) + 1;
865 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700866 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700867 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700868 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700869 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700870 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700871 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
872 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700873 break;
874 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700875 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700876 run_gc = have_zygote_space_;
877 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700878 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700879 run_gc = true;
880 break;
881 default:
882 break;
883 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700884
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700885 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700886 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700887 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800888 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700889 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700890
891 // Did we free sufficient memory for the allocation to succeed?
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700892 ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700893 if (ptr != NULL) {
894 return ptr;
895 }
896 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700897 }
898
899 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700900 // Try harder, growing the heap if necessary.
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700901 ptr = TryToAllocate(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700902 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700903 return ptr;
904 }
905
Elliott Hughes81ff3182012-03-23 20:35:56 -0700906 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
907 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
908 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700909
Elliott Hughes418dfe72011-10-06 18:56:27 -0700910 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700911 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
912 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700913
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700914 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700915 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700916 return TryToAllocate(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700917}
918
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700919void Heap::SetTargetHeapUtilization(float target) {
920 DCHECK_GT(target, 0.0f); // asserted in Java code
921 DCHECK_LT(target, 1.0f);
922 target_utilization_ = target;
923}
924
Ian Rogers1d54e732013-05-02 21:10:01 -0700925size_t Heap::GetObjectsAllocated() const {
926 size_t total = 0;
927 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
928 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
929 space::ContinuousSpace* space = *it;
930 if (space->IsDlMallocSpace()) {
931 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700932 }
933 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700934 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
935 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
936 space::DiscontinuousSpace* space = *it;
937 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
938 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700939 return total;
940}
941
Ian Rogers1d54e732013-05-02 21:10:01 -0700942size_t Heap::GetObjectsAllocatedEver() const {
943 size_t total = 0;
944 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
945 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
946 space::ContinuousSpace* space = *it;
947 if (space->IsDlMallocSpace()) {
948 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700949 }
950 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700951 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
952 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
953 space::DiscontinuousSpace* space = *it;
954 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
955 }
956 return total;
957}
958
959size_t Heap::GetBytesAllocatedEver() const {
960 size_t total = 0;
961 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
962 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
963 space::ContinuousSpace* space = *it;
964 if (space->IsDlMallocSpace()) {
965 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
966 }
967 }
968 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
969 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
970 space::DiscontinuousSpace* space = *it;
971 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
972 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700973 return total;
974}
975
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700976class InstanceCounter {
977 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800978 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700979 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800980 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700981 }
982
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800983 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800984 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800985 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800986 if (use_is_assignable_from_) {
987 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
988 ++counts_[i];
989 }
990 } else {
991 if (instance_class == classes_[i]) {
992 ++counts_[i];
993 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700994 }
995 }
996 }
997
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700998 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800999 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001000 bool use_is_assignable_from_;
1001 uint64_t* const counts_;
1002
1003 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001004};
1005
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001006void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001007 uint64_t* counts) {
1008 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1009 // is empty, so the live bitmap is the only place we need to look.
1010 Thread* self = Thread::Current();
1011 self->TransitionFromRunnableToSuspended(kNative);
1012 CollectGarbage(false);
1013 self->TransitionFromSuspendedToRunnable();
1014
1015 InstanceCounter counter(classes, use_is_assignable_from, counts);
1016 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001017 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001018}
1019
Elliott Hughes3b78c942013-01-15 17:35:41 -08001020class InstanceCollector {
1021 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001022 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001023 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1024 : class_(c), max_count_(max_count), instances_(instances) {
1025 }
1026
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001027 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1028 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001029 if (instance_class == class_) {
1030 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001031 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001032 }
1033 }
1034 }
1035
1036 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001037 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001038 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001039 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001040
1041 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1042};
1043
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001044void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1045 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001046 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1047 // is empty, so the live bitmap is the only place we need to look.
1048 Thread* self = Thread::Current();
1049 self->TransitionFromRunnableToSuspended(kNative);
1050 CollectGarbage(false);
1051 self->TransitionFromSuspendedToRunnable();
1052
1053 InstanceCollector collector(c, max_count, instances);
1054 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1055 GetLiveBitmap()->Visit(collector);
1056}
1057
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001058class ReferringObjectsFinder {
1059 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001060 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1061 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001062 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1063 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1064 }
1065
1066 // For bitmap Visit.
1067 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1068 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001069 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001070 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001071 }
1072
1073 // For MarkSweep::VisitObjectReferences.
Brian Carlstromdf629502013-07-17 22:39:56 -07001074 void operator()(const mirror::Object* referrer, const mirror::Object* object,
1075 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001076 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001077 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001078 }
1079 }
1080
1081 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001082 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001083 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001084 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001085
1086 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1087};
1088
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001089void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1090 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001091 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1092 // is empty, so the live bitmap is the only place we need to look.
1093 Thread* self = Thread::Current();
1094 self->TransitionFromRunnableToSuspended(kNative);
1095 CollectGarbage(false);
1096 self->TransitionFromSuspendedToRunnable();
1097
1098 ReferringObjectsFinder finder(o, max_count, referring_objects);
1099 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1100 GetLiveBitmap()->Visit(finder);
1101}
1102
Ian Rogers30fab402012-01-23 15:43:46 -08001103void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001104 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1105 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001106 Thread* self = Thread::Current();
1107 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001108 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001109}
1110
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001111void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001112 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001113 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1114 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001115 Thread* self = Thread::Current();
1116 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001117
1118 // Try to see if we have any Zygote spaces.
1119 if (have_zygote_space_) {
1120 return;
1121 }
1122
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001123 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1124
1125 {
1126 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001127 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001128 FlushAllocStack();
1129 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001130
Ian Rogers1d54e732013-05-02 21:10:01 -07001131 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1132 // of the remaining available heap memory.
1133 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001134 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -07001135 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001136
Ian Rogers1d54e732013-05-02 21:10:01 -07001137 // Change the GC retention policy of the zygote space to only collect when full.
1138 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1139 AddContinuousSpace(alloc_space_);
1140 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001141
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001142 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001143 for (const auto& collector : mark_sweep_collectors_) {
1144 collector->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001145 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001146}
1147
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001148void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001149 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1150 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001151 allocation_stack_->Reset();
1152}
1153
Ian Rogers1d54e732013-05-02 21:10:01 -07001154void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1155 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001156 mirror::Object** limit = stack->End();
1157 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1158 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001159 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001160 if (LIKELY(bitmap->HasAddress(obj))) {
1161 bitmap->Set(obj);
1162 } else {
1163 large_objects->Set(obj);
1164 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001165 }
1166}
1167
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001168
1169const char* gc_cause_and_type_strings[3][4] = {
1170 {"", "GC Alloc Sticky", "GC Alloc Partial", "GC Alloc Full"},
1171 {"", "GC Background Sticky", "GC Background Partial", "GC Background Full"},
1172 {"", "GC Explicit Sticky", "GC Explicit Partial", "GC Explicit Full"}};
1173
Ian Rogers1d54e732013-05-02 21:10:01 -07001174collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1175 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001176 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001177
Mathieu Chartier65db8802012-11-20 12:36:46 -08001178 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001179 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001180
Ian Rogers120f1c72012-09-28 17:17:10 -07001181 if (self->IsHandlingStackOverflow()) {
1182 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1183 }
1184
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001185 // Ensure there is only one GC at a time.
1186 bool start_collect = false;
1187 while (!start_collect) {
1188 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001189 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001190 if (!is_gc_running_) {
1191 is_gc_running_ = true;
1192 start_collect = true;
1193 }
1194 }
1195 if (!start_collect) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001196 // TODO: timinglog this.
Ian Rogers81d425b2012-09-27 16:03:43 -07001197 WaitForConcurrentGcToComplete(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001198
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001199 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1200 // Not doing at the moment to ensure soft references are cleared.
1201 }
1202 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001203 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001204
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001205 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1206 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1207 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1208 }
1209
Ian Rogers1d54e732013-05-02 21:10:01 -07001210 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001211 uint64_t gc_start_size = GetBytesAllocated();
1212 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001213 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001214 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1215 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001216 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001217 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001218 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001219 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1220 }
1221
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001222 if (gc_type == collector::kGcTypeSticky &&
1223 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1224 gc_type = collector::kGcTypePartial;
1225 }
1226
Ian Rogers1d54e732013-05-02 21:10:01 -07001227 DCHECK_LT(gc_type, collector::kGcTypeMax);
1228 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001229 DCHECK_LE(gc_cause, kGcCauseExplicit);
1230
1231 ATRACE_BEGIN(gc_cause_and_type_strings[gc_cause][gc_type]);
1232
Ian Rogers1d54e732013-05-02 21:10:01 -07001233 collector::MarkSweep* collector = NULL;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001234 for (const auto& cur_collector : mark_sweep_collectors_) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001235 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1236 collector = cur_collector;
1237 break;
1238 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001239 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001240 CHECK(collector != NULL)
1241 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1242 << " and type=" << gc_type;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001243
1244 base::TimingLogger& timings = collector->GetTimings();
1245
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001246 collector->clear_soft_references_ = clear_soft_references;
1247 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001248 total_objects_freed_ever_ += collector->GetFreedObjects();
1249 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001250
Ian Rogers1d54e732013-05-02 21:10:01 -07001251 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001252 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1253 bool was_slow = duration > kSlowGcThreshold ||
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001254 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001255 for (size_t i = 0; i < pauses.size(); ++i) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001256 if (pauses[i] > kLongGcPauseThreshold) {
1257 was_slow = true;
1258 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001259 }
1260
Anwar Ghuloumba041a52013-08-16 13:05:05 -07001261 if (was_slow && care_about_pause_times_) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001262 const size_t percent_free = GetPercentFree();
1263 const size_t current_heap_size = GetBytesAllocated();
1264 const size_t total_memory = GetTotalMemory();
1265 std::ostringstream pause_string;
1266 for (size_t i = 0; i < pauses.size(); ++i) {
1267 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1268 << ((i != pauses.size() - 1) ? ", " : "");
1269 }
1270 LOG(INFO) << gc_cause << " " << collector->GetName()
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001271 << " GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001272 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1273 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1274 << " total " << PrettyDuration((duration / 1000) * 1000);
1275 if (VLOG_IS_ON(heap)) {
1276 LOG(INFO) << Dumpable<base::TimingLogger>(timings);
1277 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001278 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001279
Ian Rogers15bf2d32012-08-28 17:33:04 -07001280 {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001281 MutexLock mu(self, *gc_complete_lock_);
1282 is_gc_running_ = false;
1283 last_gc_type_ = gc_type;
1284 // Wake anyone who may have been waiting for the GC to complete.
1285 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001286 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001287
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001288 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001289
1290 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001291 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001292 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001293}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001294
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001295void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::TimingLogger& timings,
Ian Rogers1d54e732013-05-02 21:10:01 -07001296 collector::GcType gc_type) {
1297 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001298 // 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 -07001299 // cards.
1300 return;
1301 }
1302
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001303 base::TimingLogger::ScopedSplit split("UpdateModUnionTable", &timings);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001304 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001305 if (gc_type == collector::kGcTypePartial) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001306 base::TimingLogger::ScopedSplit split("UpdateZygoteModUnionTable", &timings);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001307 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001308
Ian Rogers1d54e732013-05-02 21:10:01 -07001309 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001310 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001311 }
1312
1313 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001314 timings.NewSplit("UpdateModUnionTable");
1315 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001316
1317 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001318 timings.NewSplit("MarkImageToAllocSpaceReferences");
1319 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001320}
1321
Ian Rogers1d54e732013-05-02 21:10:01 -07001322static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001323 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001324 if (root == obj) {
1325 LOG(INFO) << "Object " << obj << " is a root";
1326 }
1327}
1328
1329class ScanVisitor {
1330 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001331 void operator()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001332 LOG(INFO) << "Would have rescanned object " << obj;
1333 }
1334};
1335
Ian Rogers1d54e732013-05-02 21:10:01 -07001336// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001337class VerifyReferenceVisitor {
1338 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001339 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001340 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001341 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001342
1343 bool Failed() const {
1344 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001345 }
1346
1347 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001348 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001349 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1350 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001351 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001352 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001353 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1354 accounting::CardTable* card_table = heap_->GetCardTable();
1355 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1356 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001357
Ian Rogers1d54e732013-05-02 21:10:01 -07001358 if (obj != NULL) {
1359 byte* card_addr = card_table->CardFromAddr(obj);
1360 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1361 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1362 << "\nObj type " << PrettyTypeOf(obj)
1363 << "\nRef type " << PrettyTypeOf(ref);
1364 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1365 void* cover_begin = card_table->AddrFromCard(card_addr);
1366 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1367 accounting::CardTable::kCardSize);
1368 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1369 << "-" << cover_end;
1370 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001371
Ian Rogers1d54e732013-05-02 21:10:01 -07001372 // Print out how the object is live.
1373 if (bitmap != NULL && bitmap->Test(obj)) {
1374 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1375 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001376 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001377 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1378 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001379 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001380 LOG(ERROR) << "Object " << obj << " found in live stack";
1381 }
1382 // Attempt to see if the card table missed the reference.
1383 ScanVisitor scan_visitor;
1384 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1385 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001386 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001387
1388 // Search to see if any of the roots reference our object.
1389 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1390 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1391
1392 // Search to see if any of the roots reference our reference.
1393 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1394 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1395 } else {
1396 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001397 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001398 if (alloc_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001399 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001400 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001401 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001402 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001403 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001404 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1405 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1406 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001407 }
1408 }
1409
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001410 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001411 return heap_->IsLiveObjectLocked(obj);
1412 }
1413
1414 static void VerifyRoots(const mirror::Object* root, void* arg) {
1415 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1416 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001417 }
1418
1419 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001420 Heap* const heap_;
1421 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001422};
1423
Ian Rogers1d54e732013-05-02 21:10:01 -07001424// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001425class VerifyObjectVisitor {
1426 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001427 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001428
Brian Carlstromdf629502013-07-17 22:39:56 -07001429 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001430 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001431 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1432 // be live or else how did we find it in the live bitmap?
1433 VerifyReferenceVisitor visitor(heap_);
1434 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1435 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001436 }
1437
1438 bool Failed() const {
1439 return failed_;
1440 }
1441
1442 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001443 Heap* const heap_;
1444 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001445};
1446
1447// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001448bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001449 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001450 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001451 allocation_stack_->Sort();
1452 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001453 // Perform the verification.
1454 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001455 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001456 GetLiveBitmap()->Visit(visitor);
1457 // We don't want to verify the objects in the allocation stack since they themselves may be
1458 // pointing to dead objects if they are not reachable.
1459 if (visitor.Failed()) {
1460 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001461 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001462 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001463 return true;
1464}
1465
1466class VerifyReferenceCardVisitor {
1467 public:
1468 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1469 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1470 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001471 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001472 }
1473
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001474 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1475 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001476 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1477 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001478 // Filter out class references since changing an object's class does not mark the card as dirty.
1479 // Also handles large objects, since the only reference they hold is a class reference.
1480 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001481 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001482 // If the object is not dirty and it is referencing something in the live stack other than
1483 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001484 if (!card_table->AddrIsInCardTable(obj)) {
1485 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1486 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001487 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001488 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1489 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001490 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001491 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1492 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001493 LOG(ERROR) << "Object " << obj << " found in live stack";
1494 }
1495 if (heap_->GetLiveBitmap()->Test(obj)) {
1496 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1497 }
1498 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1499 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1500
1501 // Print which field of the object is dead.
1502 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001503 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001504 CHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001505 const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
1506 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001507 CHECK(fields != NULL);
1508 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001509 const mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001510 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1511 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1512 << PrettyField(cur);
1513 break;
1514 }
1515 }
1516 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001517 const mirror::ObjectArray<mirror::Object>* object_array =
1518 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001519 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1520 if (object_array->Get(i) == ref) {
1521 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1522 }
1523 }
1524 }
1525
1526 *failed_ = true;
1527 }
1528 }
1529 }
1530 }
1531
1532 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001533 Heap* const heap_;
1534 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001535};
1536
1537class VerifyLiveStackReferences {
1538 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001539 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001540 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001541 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001542
Brian Carlstromdf629502013-07-17 22:39:56 -07001543 void operator()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001544 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1545 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001546 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001547 }
1548
1549 bool Failed() const {
1550 return failed_;
1551 }
1552
1553 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001554 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001555 bool failed_;
1556};
1557
1558bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001559 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001560
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001561 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001562 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001563 VerifyLiveStackReferences visitor(this);
1564 GetLiveBitmap()->Visit(visitor);
1565
1566 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001567 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001568 visitor(*it);
1569 }
1570
1571 if (visitor.Failed()) {
1572 DumpSpaces();
1573 return false;
1574 }
1575 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001576}
1577
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001578void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001579 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001580
1581 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001582 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001583 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001584 }
1585}
1586
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001587void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001588 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001589 for (const auto& space : continuous_spaces_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001590 if (space->IsImageSpace()) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001591 base::TimingLogger::ScopedSplit split("ImageModUnionClearCards", &timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07001592 image_mod_union_table_->ClearCards(space);
1593 } else if (space->IsZygoteSpace()) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001594 base::TimingLogger::ScopedSplit split("ZygoteModUnionClearCards", &timings);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001595 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001596 } else {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001597 base::TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001598 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1599 // were dirty before the GC started.
1600 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) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001647 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1648 // reachable objects.
1649 if (verify_post_gc_heap_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001650 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001651 Thread* self = Thread::Current();
1652 CHECK_NE(self->GetState(), kRunnable);
1653 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001654 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001655 {
1656 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1657 // Swapping bound bitmaps does nothing.
1658 gc->SwapBitmaps();
1659 if (!VerifyHeapReferences()) {
1660 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1661 }
1662 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001663 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001664 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001665 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001666 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001667}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001668
Ian Rogers1d54e732013-05-02 21:10:01 -07001669void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001670 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001671 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001672 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001673 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001674 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001675 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001676}
1677
Ian Rogers1d54e732013-05-02 21:10:01 -07001678collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1679 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001680 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001681 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001682 bool do_wait;
1683 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001684 {
1685 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001686 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001687 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001688 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001689 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001690 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001691 // We must wait, change thread state then sleep on gc_complete_cond_;
1692 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1693 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001694 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001695 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001696 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001697 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001698 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001699 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001700 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001701 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001702 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001703 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1704 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001705 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001706 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001707 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001708 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001709}
1710
Elliott Hughesc967f782012-04-16 10:23:15 -07001711void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001712 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001713 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001714 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001715}
1716
1717size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001718 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001719}
1720
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001721void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001722 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001723 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001724 << PrettySize(GetMaxMemory());
1725 max_allowed_footprint = GetMaxMemory();
1726 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001727 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001728}
1729
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001730void Heap::UpdateMaxNativeFootprint() {
1731 size_t native_size = native_bytes_allocated_;
1732 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1733 size_t target_size = native_size / GetTargetHeapUtilization();
1734 if (target_size > native_size + max_free_) {
1735 target_size = native_size + max_free_;
1736 } else if (target_size < native_size + min_free_) {
1737 target_size = native_size + min_free_;
1738 }
1739 native_footprint_gc_watermark_ = target_size;
1740 native_footprint_limit_ = 2 * target_size - native_size;
1741}
1742
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001743void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001744 // We know what our utilization is at this moment.
1745 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001746 const size_t bytes_allocated = GetBytesAllocated();
1747 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001748 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001749
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001750 size_t target_size;
1751 if (gc_type != collector::kGcTypeSticky) {
1752 // Grow the heap for non sticky GC.
1753 target_size = bytes_allocated / GetTargetHeapUtilization();
1754 if (target_size > bytes_allocated + max_free_) {
1755 target_size = bytes_allocated + max_free_;
1756 } else if (target_size < bytes_allocated + min_free_) {
1757 target_size = bytes_allocated + min_free_;
1758 }
1759 next_gc_type_ = collector::kGcTypeSticky;
1760 } else {
1761 // Based on how close the current heap size is to the target size, decide
1762 // whether or not to do a partial or sticky GC next.
1763 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1764 next_gc_type_ = collector::kGcTypeSticky;
1765 } else {
1766 next_gc_type_ = collector::kGcTypePartial;
1767 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001768
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001769 // If we have freed enough memory, shrink the heap back down.
1770 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1771 target_size = bytes_allocated + max_free_;
1772 } else {
1773 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1774 }
1775 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001776 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001777
Ian Rogers1d54e732013-05-02 21:10:01 -07001778 // Calculate when to perform the next ConcurrentGC.
1779 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001780 // Calculate the estimated GC duration.
1781 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1782 // Estimate how many remaining bytes we will have when we need to start the next GC.
1783 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001784 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1785 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1786 // A never going to happen situation that from the estimated allocation rate we will exceed
1787 // the applications entire footprint with the given estimated allocation rate. Schedule
1788 // another GC straight away.
1789 concurrent_start_bytes_ = bytes_allocated;
1790 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001791 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1792 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1793 // right away.
1794 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001795 }
1796 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1797 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1798 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001799
1800 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001801}
1802
jeffhaoc1160702011-10-27 15:48:45 -07001803void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001804 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001805 alloc_space_->ClearGrowthLimit();
1806}
1807
Elliott Hughesadb460d2011-10-05 17:02:34 -07001808void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001809 MemberOffset reference_queue_offset,
1810 MemberOffset reference_queueNext_offset,
1811 MemberOffset reference_pendingNext_offset,
1812 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001813 reference_referent_offset_ = reference_referent_offset;
1814 reference_queue_offset_ = reference_queue_offset;
1815 reference_queueNext_offset_ = reference_queueNext_offset;
1816 reference_pendingNext_offset_ = reference_pendingNext_offset;
1817 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1818 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1819 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1820 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1821 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1822 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1823}
1824
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001825mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001826 DCHECK(reference != NULL);
1827 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001828 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001829}
1830
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001831void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001832 DCHECK(reference != NULL);
1833 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1834 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1835}
1836
1837// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001838bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001839 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001840 const mirror::Object* queue =
1841 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1842 const mirror::Object* queue_next =
1843 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001844 return (queue != NULL) && (queue_next == NULL);
1845}
1846
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001847void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001848 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001849 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1850 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001851 EnqueuePendingReference(ref, cleared_reference_list);
1852}
1853
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001854void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001855 DCHECK(ref != NULL);
1856 DCHECK(list != NULL);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001857 mirror::Object* pending =
1858 ref->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
1859 if (pending == NULL) {
1860 if (*list == NULL) {
1861 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1862 *list = ref;
1863 } else {
1864 mirror::Object* head =
1865 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
1866 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1867 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1868 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001869 }
1870}
1871
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001872mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001873 DCHECK(list != NULL);
1874 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001875 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1876 false);
1877 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001878
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001879 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1880 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001881 if (*list == head) {
1882 ref = *list;
1883 *list = NULL;
1884 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001885 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1886 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001887 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1888 ref = head;
1889 }
1890 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1891 return ref;
1892}
1893
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001894void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001895 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001896 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001897 ArgArray arg_array(NULL, 0);
1898 arg_array.Append(reinterpret_cast<uint32_t>(object));
1899 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001900 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001901}
1902
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001903void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001904 DCHECK(cleared != NULL);
1905 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001906 // When a runtime isn't started there are no reference queues to care about so ignore.
1907 if (LIKELY(Runtime::Current()->IsStarted())) {
1908 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001909 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001910 ArgArray arg_array(NULL, 0);
1911 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1912 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001913 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001914 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001915 *cleared = NULL;
1916 }
1917}
1918
Ian Rogers1f539342012-10-03 21:09:42 -07001919void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001920 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001921 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001922 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001923 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001924 !runtime->IsConcurrentGcEnabled()) {
1925 return;
1926 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001927 {
1928 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1929 if (runtime->IsShuttingDown()) {
1930 return;
1931 }
1932 }
1933 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001934 return;
1935 }
1936
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001937 // We already have a request pending, no reason to start more until we update
1938 // concurrent_start_bytes_.
1939 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1940
Ian Rogers120f1c72012-09-28 17:17:10 -07001941 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001942 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1943 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001944 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1945 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001946 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001947}
1948
Ian Rogers81d425b2012-09-27 16:03:43 -07001949void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001950 {
1951 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001952 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001953 return;
1954 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001955 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001956
Mathieu Chartier65db8802012-11-20 12:36:46 -08001957 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001958 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001959 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001960 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001961}
1962
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001963void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001964 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1965 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1966 // a space it will hold its lock and can become a cause of jank.
1967 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1968 // forking.
1969
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001970 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1971 // because that only marks object heads, so a large array looks like lots of empty space. We
1972 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1973 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1974 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1975 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001976 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001977 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001978 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
Mathieu Chartiere0a53e92013-08-05 10:17:40 -07001979 if ((utilization > 0.75f && !IsLowMemoryMode()) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
1980 // Don't bother trimming the alloc space if it's more than 75% utilized and low memory mode is
1981 // not enabled, or if a heap trim occurred in the last two seconds.
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001982 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001983 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001984
1985 Thread* self = Thread::Current();
1986 {
1987 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1988 Runtime* runtime = Runtime::Current();
1989 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1990 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1991 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1992 // as we don't hold the lock while requesting the trim).
1993 return;
1994 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001995 }
Ian Rogers48931882013-01-22 14:35:16 -08001996
Ian Rogers1d54e732013-05-02 21:10:01 -07001997 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07001998 ListenForProcessStateChange();
1999
2000 // Trim only if we do not currently care about pause times.
2001 if (!care_about_pause_times_) {
2002 JNIEnv* env = self->GetJniEnv();
2003 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2004 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2005 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2006 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2007 CHECK(!env->ExceptionCheck());
2008 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002009}
2010
Ian Rogers48931882013-01-22 14:35:16 -08002011size_t Heap::Trim() {
2012 // Handle a requested heap trim on a thread outside of the main GC thread.
2013 return alloc_space_->Trim();
2014}
2015
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002016bool Heap::IsGCRequestPending() const {
2017 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2018}
2019
2020void Heap::RegisterNativeAllocation(int bytes) {
2021 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002022 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002023 Thread* self = Thread::Current();
2024 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
2025 // The second watermark is higher than the gc watermark. If you hit this it means you are
2026 // allocating native objects faster than the GC can keep up with.
2027 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2028 JNIEnv* env = self->GetJniEnv();
2029 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
2030 // point.
2031 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
2032 DCHECK(WellKnownClasses::java_lang_System != NULL);
2033 WellKnownClasses::java_lang_System_runFinalization =
2034 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2035 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
2036 }
2037 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
2038 // Just finished a GC, attempt to run finalizers.
2039 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2040 WellKnownClasses::java_lang_System_runFinalization);
2041 CHECK(!env->ExceptionCheck());
2042 }
2043
2044 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2045 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2046 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
2047 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2048 WellKnownClasses::java_lang_System_runFinalization);
2049 CHECK(!env->ExceptionCheck());
2050 }
2051 // We have just run finalizers, update the native watermark since it is very likely that
2052 // finalizers released native managed allocations.
2053 UpdateMaxNativeFootprint();
2054 } else {
2055 if (!IsGCRequestPending()) {
2056 RequestConcurrentGC(self);
2057 }
2058 }
2059 }
2060}
2061
2062void Heap::RegisterNativeFree(int bytes) {
2063 int expected_size, new_size;
2064 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002065 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002066 new_size = expected_size - bytes;
2067 if (new_size < 0) {
2068 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
2069 bytes, expected_size);
2070 break;
2071 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002072 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002073}
2074
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002075int64_t Heap::GetTotalMemory() const {
2076 int64_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002077 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002078 if (space->IsImageSpace()) {
2079 // Currently don't include the image space.
2080 } else if (space->IsDlMallocSpace()) {
2081 // Zygote or alloc space
2082 ret += space->AsDlMallocSpace()->GetFootprint();
2083 }
2084 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002085 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002086 if (space->IsLargeObjectSpace()) {
2087 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2088 }
2089 }
2090 return ret;
2091}
2092
Ian Rogers1d54e732013-05-02 21:10:01 -07002093} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002094} // namespace art