blob: 804c66932e3141ac4c589bdc28b146b052d58562 [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"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070042#include "heap-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070043#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080044#include "invoke_arg_array_builder.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070045#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "mirror/object.h"
48#include "mirror/object-inl.h"
49#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080050#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080051#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070052#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070053#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070054#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070055#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070056#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070057#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070058
59namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070060namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070061
Mathieu Chartier720ef762013-08-17 14:46:54 -070062static constexpr bool kGCALotMode = false;
63static constexpr size_t kGcAlotInterval = KB;
64static constexpr bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070065// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070066static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070067
Mathieu Chartier0051be62012-10-12 17:47:11 -070068Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Ian Rogers8d31bbd2013-10-13 10:44:14 -070069 double target_utilization, size_t capacity, const std::string& image_file_name,
Mathieu Chartier2775ee42013-08-20 17:43:47 -070070 bool concurrent_gc, size_t parallel_gc_threads, size_t conc_gc_threads,
71 bool low_memory_mode, size_t long_pause_log_threshold, size_t long_gc_log_threshold,
72 bool ignore_max_footprint)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070073 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080074 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070075 concurrent_gc_(concurrent_gc),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070076 parallel_gc_threads_(parallel_gc_threads),
77 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070078 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070079 long_pause_log_threshold_(long_pause_log_threshold),
80 long_gc_log_threshold_(long_gc_log_threshold),
81 ignore_max_footprint_(ignore_max_footprint),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070082 have_zygote_space_(false),
Mathieu Chartier94c32c52013-08-09 11:14:04 -070083 soft_ref_queue_lock_(NULL),
84 weak_ref_queue_lock_(NULL),
85 finalizer_ref_queue_lock_(NULL),
86 phantom_ref_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080087 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -070088 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -070089 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -080090 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070091 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -070092 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -070093 native_footprint_gc_watermark_(initial_size),
94 native_footprint_limit_(2 * initial_size),
Mathieu Chartierc39e3422013-08-07 16:41:36 -070095 activity_thread_class_(NULL),
96 application_thread_class_(NULL),
97 activity_thread_(NULL),
98 application_thread_(NULL),
99 last_process_state_id_(NULL),
100 // Initially care about pauses in case we never get notified of process states, or if the JNI
101 // code becomes broken.
102 care_about_pause_times_(true),
Mathieu Chartier720ef762013-08-17 14:46:54 -0700103 concurrent_start_bytes_(concurrent_gc_ ? initial_size - kMinConcurrentRemainingBytes
104 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700105 total_bytes_freed_ever_(0),
106 total_objects_freed_ever_(0),
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 if (!image_file_name.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700148 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700149 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700150 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800151 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
152 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800153 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
154 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700155 if (oat_file_end_addr > requested_alloc_space_begin) {
156 requested_alloc_space_begin =
157 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
158 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700159 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700160 }
161
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700162 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700163 initial_size,
164 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700165 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700166 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700167 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700168 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700169
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700170 // Allocate the large object space.
171 const bool kUseFreeListSpaceForLOS = false;
172 if (kUseFreeListSpaceForLOS) {
173 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
174 } else {
175 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
176 }
177 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
178 AddDiscontinuousSpace(large_object_space_);
179
Ian Rogers1d54e732013-05-02 21:10:01 -0700180 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
181 byte* heap_begin = continuous_spaces_.front()->Begin();
182 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
183 if (continuous_spaces_.back()->IsDlMallocSpace()) {
184 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700185 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700186
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800187 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700188 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700189 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700190
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700191 accounting::ModUnionTable* mod_union_table =
192 new accounting::ModUnionTableToZygoteAllocspace("Image mod-union table", this,
193 GetImageSpace());
194 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
195 AddModUnionTable(mod_union_table);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700196
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700197 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700198 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700199
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800200 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700201 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700202 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
203 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
204 max_allocation_stack_size_));
205 live_stack_.reset(accounting::ObjectStack::Create("live stack",
206 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700207
Mathieu Chartier65db8802012-11-20 12:36:46 -0800208 // It's still too early to take a lock because there are no threads yet, but we can create locks
209 // now. We don't create it earlier to make it clear that you can't use locks during heap
210 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700211 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700212 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
213 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700214
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700215 // Create the reference queue locks, this is required so for parallel object scanning in the GC.
216 soft_ref_queue_lock_ = new Mutex("Soft reference queue lock");
217 weak_ref_queue_lock_ = new Mutex("Weak reference queue lock");
218 finalizer_ref_queue_lock_ = new Mutex("Finalizer reference queue lock");
219 phantom_ref_queue_lock_ = new Mutex("Phantom reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700220
Ian Rogers1d54e732013-05-02 21:10:01 -0700221 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800222 last_gc_size_ = GetBytesAllocated();
223
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700224 if (ignore_max_footprint_) {
225 SetIdealFootprint(std::numeric_limits<size_t>::max());
226 concurrent_start_bytes_ = max_allowed_footprint_;
227 }
228
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800229 // Create our garbage collectors.
230 for (size_t i = 0; i < 2; ++i) {
231 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700232 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
233 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
234 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700235 }
236
Brian Carlstrom42748892013-07-18 18:04:08 -0700237 CHECK_NE(max_allowed_footprint_, 0U);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700238
239 if (running_on_valgrind_) {
240 Runtime::Current()->InstrumentQuickAllocEntryPoints();
241 }
242
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800243 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800244 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700245 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700246}
247
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700248void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700249 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
250 if (num_threads != 0) {
251 thread_pool_.reset(new ThreadPool(num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700252 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700253}
254
255void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700256 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700257}
258
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700259static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
260 CHECK(out_value != NULL);
261 jfieldID field = env->GetStaticFieldID(clz, name, "I");
262 if (field == NULL) {
263 env->ExceptionClear();
264 return false;
265 }
266 *out_value = env->GetStaticIntField(clz, field);
267 return true;
268}
269
270void Heap::ListenForProcessStateChange() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700271 VLOG(heap) << "Heap notified of process state change";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700272
273 Thread* self = Thread::Current();
274 JNIEnvExt* env = self->GetJniEnv();
275
276 if (!have_zygote_space_) {
277 return;
278 }
279
280 if (activity_thread_class_ == NULL) {
281 jclass clz = env->FindClass("android/app/ActivityThread");
282 if (clz == NULL) {
283 env->ExceptionClear();
284 LOG(WARNING) << "Could not find activity thread class in process state change";
285 return;
286 }
287 activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
288 }
289
290 if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
291 jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
292 "currentActivityThread",
293 "()Landroid/app/ActivityThread;");
294 if (current_activity_method == NULL) {
295 env->ExceptionClear();
296 LOG(WARNING) << "Could not get method for currentActivityThread";
297 return;
298 }
299
300 jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
301 if (obj == NULL) {
302 env->ExceptionClear();
303 LOG(WARNING) << "Could not get current activity";
304 return;
305 }
306 activity_thread_ = env->NewGlobalRef(obj);
307 }
308
309 if (process_state_cares_about_pause_time_.empty()) {
310 // Just attempt to do this the first time.
311 jclass clz = env->FindClass("android/app/ActivityManager");
312 if (clz == NULL) {
313 LOG(WARNING) << "Activity manager class is null";
314 return;
315 }
316 ScopedLocalRef<jclass> activity_manager(env, clz);
317 std::vector<const char*> care_about_pauses;
318 care_about_pauses.push_back("PROCESS_STATE_TOP");
319 care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
320 // Attempt to read the constants and classify them as whether or not we care about pause times.
321 for (size_t i = 0; i < care_about_pauses.size(); ++i) {
322 int process_state = 0;
323 if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
324 process_state_cares_about_pause_time_.insert(process_state);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700325 VLOG(heap) << "Adding process state " << process_state
326 << " to set of states which care about pause time";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700327 }
328 }
329 }
330
331 if (application_thread_class_ == NULL) {
332 jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
333 if (clz == NULL) {
334 env->ExceptionClear();
335 LOG(WARNING) << "Could not get application thread class";
336 return;
337 }
338 application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
339 last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
340 if (last_process_state_id_ == NULL) {
341 env->ExceptionClear();
342 LOG(WARNING) << "Could not get last process state member";
343 return;
344 }
345 }
346
347 if (application_thread_class_ != NULL && application_thread_ == NULL) {
348 jmethodID get_application_thread =
349 env->GetMethodID(activity_thread_class_, "getApplicationThread",
350 "()Landroid/app/ActivityThread$ApplicationThread;");
351 if (get_application_thread == NULL) {
352 LOG(WARNING) << "Could not get method ID for get application thread";
353 return;
354 }
355
356 jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
357 if (obj == NULL) {
358 LOG(WARNING) << "Could not get application thread";
359 return;
360 }
361
362 application_thread_ = env->NewGlobalRef(obj);
363 }
364
365 if (application_thread_ != NULL && last_process_state_id_ != NULL) {
366 int process_state = env->GetIntField(application_thread_, last_process_state_id_);
367 env->ExceptionClear();
368
369 care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
370 process_state_cares_about_pause_time_.end();
371
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700372 VLOG(heap) << "New process state " << process_state
373 << " care about pauses " << care_about_pause_times_;
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700374 }
Mathieu Chartier82353312013-07-18 10:47:51 -0700375}
376
Ian Rogers1d54e732013-05-02 21:10:01 -0700377void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700378 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700379 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700380 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700381 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700382 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700383 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
384 continuous_spaces_.push_back(space);
385 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
386 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700387 }
388
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700389 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700390 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
391 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
392 return a->Begin() < b->Begin();
393 });
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700394
395 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
396 // avoid redundant marking.
397 bool seen_zygote = false, seen_alloc = false;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700398 for (const auto& space : continuous_spaces_) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700399 if (space->IsImageSpace()) {
400 DCHECK(!seen_zygote);
401 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700402 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700403 DCHECK(!seen_alloc);
404 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700405 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700406 seen_alloc = true;
407 }
408 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800409}
410
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700411void Heap::RegisterGCAllocation(size_t bytes) {
412 if (this != NULL) {
413 gc_memory_overhead_.fetch_add(bytes);
414 }
415}
416
417void Heap::RegisterGCDeAllocation(size_t bytes) {
418 if (this != NULL) {
419 gc_memory_overhead_.fetch_sub(bytes);
420 }
421}
422
Ian Rogers1d54e732013-05-02 21:10:01 -0700423void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
424 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
425 DCHECK(space != NULL);
426 DCHECK(space->GetLiveObjects() != NULL);
427 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
428 DCHECK(space->GetMarkObjects() != NULL);
429 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
430 discontinuous_spaces_.push_back(space);
431}
432
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700433void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700434 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700435 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700436 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800437
438 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800439 uint64_t total_paused_time = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700440 for (const auto& collector : mark_sweep_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800441 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800442 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700443 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800444 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700445 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800446 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
447 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
448 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700449 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
450 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
451 << collector->GetName() << " freed: " << freed_objects
452 << " objects with total size " << PrettySize(freed_bytes) << "\n"
453 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
454 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800455 total_duration += total_ns;
456 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700457 }
458 }
459 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700460 size_t total_objects_allocated = GetObjectsAllocatedEver();
461 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700462 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700463 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700464 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
465 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700466 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700467 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700468 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700469 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700470 os << "Total number of allocations: " << total_objects_allocated << "\n";
471 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700472 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700473 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
474 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
475 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700476 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700477 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
478 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700479 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700480}
481
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800482Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700483 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700484 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700485 }
486
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800487 STLDeleteElements(&mark_sweep_collectors_);
488
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700489 // If we don't reset then the mark stack complains in it's destructor.
490 allocation_stack_->Reset();
491 live_stack_->Reset();
492
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800493 VLOG(heap) << "~Heap()";
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700494 STLDeleteValues(&mod_union_tables_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700495 STLDeleteElements(&continuous_spaces_);
496 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700497 delete gc_complete_lock_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700498 delete soft_ref_queue_lock_;
499 delete weak_ref_queue_lock_;
500 delete finalizer_ref_queue_lock_;
501 delete phantom_ref_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700502}
503
Ian Rogers1d54e732013-05-02 21:10:01 -0700504space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
505 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700506 for (const auto& space : continuous_spaces_) {
507 if (space->Contains(obj)) {
508 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700509 }
510 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700511 if (!fail_ok) {
512 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
513 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700514 return NULL;
515}
516
Ian Rogers1d54e732013-05-02 21:10:01 -0700517space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
518 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700519 for (const auto& space : discontinuous_spaces_) {
520 if (space->Contains(obj)) {
521 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700522 }
523 }
524 if (!fail_ok) {
525 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
526 }
527 return NULL;
528}
529
530space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
531 space::Space* result = FindContinuousSpaceFromObject(obj, true);
532 if (result != NULL) {
533 return result;
534 }
535 return FindDiscontinuousSpaceFromObject(obj, true);
536}
537
538space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700539 for (const auto& space : continuous_spaces_) {
540 if (space->IsImageSpace()) {
541 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700542 }
543 }
544 return NULL;
545}
546
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700547static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700548 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700549 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700550 size_t chunk_free_bytes = chunk_size - used_bytes;
551 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
552 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700553 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700554}
555
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700556void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, bool large_object_allocation) {
557 std::ostringstream oss;
558 int64_t total_bytes_free = GetFreeMemory();
559 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
560 << " free bytes";
561 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
562 if (!large_object_allocation && total_bytes_free >= byte_count) {
563 size_t max_contiguous_allocation = 0;
564 for (const auto& space : continuous_spaces_) {
565 if (space->IsDlMallocSpace()) {
566 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
567 }
568 }
569 oss << "; failed due to fragmentation (largest possible contiguous allocation "
570 << max_contiguous_allocation << " bytes)";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700571 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700572 self->ThrowOutOfMemoryError(oss.str().c_str());
573}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700574
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700575inline bool Heap::TryAllocLargeObjectInstrumented(Thread* self, mirror::Class* c, size_t byte_count,
576 mirror::Object** obj_ptr, size_t* bytes_allocated) {
577 bool large_object_allocation = ShouldAllocLargeObject(c, byte_count);
Ian Rogers333cf1b2013-07-24 11:57:02 -0700578 if (UNLIKELY(large_object_allocation)) {
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700579 mirror::Object* obj = AllocateInstrumented(self, large_object_space_, byte_count, bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700580 // Make sure that our large object didn't get placed anywhere within the space interval or else
581 // it breaks the immune range.
582 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700583 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
584 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700585 *obj_ptr = obj;
586 }
587 return large_object_allocation;
588}
589
590mirror::Object* Heap::AllocObjectInstrumented(Thread* self, mirror::Class* c, size_t byte_count) {
591 DebugCheckPreconditionsForAllobObject(c, byte_count);
592 mirror::Object* obj;
593 size_t bytes_allocated;
594 AllocationTimer alloc_timer(this, &obj);
595 bool large_object_allocation = TryAllocLargeObjectInstrumented(self, c, byte_count,
596 &obj, &bytes_allocated);
597 if (LIKELY(!large_object_allocation)) {
598 // Non-large object allocation.
599 obj = AllocateInstrumented(self, alloc_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700600 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700601 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700602 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700603 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700604 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700605 // Record allocation after since we want to use the atomic add for the atomic fence to guard
606 // the SetClass since we do not want the class to appear NULL in another thread.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700607 size_t new_num_bytes_allocated = RecordAllocationInstrumented(bytes_allocated, obj);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608 if (Dbg::IsAllocTrackingEnabled()) {
609 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700610 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700611 CheckConcurrentGC(self, new_num_bytes_allocated, obj);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700612 if (kDesiredHeapVerification > kNoHeapVerification) {
613 VerifyObject(obj);
614 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700615 return obj;
Carl Shapiro58551df2011-07-24 03:09:51 -0700616 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700617 ThrowOutOfMemoryError(self, byte_count, large_object_allocation);
618 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700619}
620
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800621bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700622 // Note: we deliberately don't take the lock here, and mustn't test anything that would
623 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700624 if (obj == NULL) {
625 return true;
626 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700627 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700628 return false;
629 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700630 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700631}
632
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700633bool Heap::IsLiveObjectLocked(const mirror::Object* obj, bool search_allocation_stack,
634 bool search_live_stack, bool sorted) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700635 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700636 if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700637 return false;
638 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700639 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
640 space::DiscontinuousSpace* d_space = NULL;
641 if (c_space != NULL) {
642 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700643 return true;
644 }
645 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700646 d_space = FindDiscontinuousSpaceFromObject(obj, true);
647 if (d_space != NULL) {
648 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700649 return true;
650 }
651 }
652 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700653 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700654 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
655 if (i > 0) {
656 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -0700657 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700658
659 if (search_allocation_stack) {
660 if (sorted) {
661 if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
662 return true;
663 }
664 } else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
665 return true;
666 }
667 }
668
669 if (search_live_stack) {
670 if (sorted) {
671 if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
672 return true;
673 }
674 } else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
675 return true;
676 }
677 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700678 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700679 // We need to check the bitmaps again since there is a race where we mark something as live and
680 // then clear the stack containing it.
681 if (c_space != NULL) {
682 if (c_space->GetLiveBitmap()->Test(obj)) {
683 return true;
684 }
685 } else {
686 d_space = FindDiscontinuousSpaceFromObject(obj, true);
687 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
688 return true;
689 }
690 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700691 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700692}
693
Ian Rogers04d7aa92013-03-16 14:29:17 -0700694void Heap::VerifyObjectImpl(const mirror::Object* obj) {
695 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700696 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700697 return;
698 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700699 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700700}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700701
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700702void Heap::DumpSpaces() {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700703 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700704 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
705 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700706 LOG(INFO) << space << " " << *space << "\n"
707 << live_bitmap << " " << *live_bitmap << "\n"
708 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700709 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700710 for (const auto& space : discontinuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700711 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700712 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700713}
714
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800715void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700716 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
717 // Ignore early dawn of the universe verifications.
718 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.load()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800719 return;
720 }
721 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
722 mirror::Object::ClassOffset().Int32Value();
723 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
724 if (UNLIKELY(c == NULL)) {
725 LOG(FATAL) << "Null class in object: " << obj;
726 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
727 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
728 }
729 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
730 // Note: we don't use the accessors here as they have internal sanity checks
731 // that we don't want to run
732 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
733 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
734 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
735 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
736 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700737
Ian Rogers62d6c772013-02-27 08:32:07 -0800738 if (verify_object_mode_ != kVerifyAllFast) {
739 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
740 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700741 if (!IsLiveObjectLocked(obj)) {
742 DumpSpaces();
743 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700744 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700745 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700746 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
747 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700748 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700749}
750
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800751void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700752 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700753 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700754}
755
756void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700757 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700758 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700759}
760
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700761inline size_t Heap::RecordAllocationInstrumented(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700762 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700763 DCHECK_GT(size, 0u);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700764 size_t old_num_bytes_allocated = static_cast<size_t>(num_bytes_allocated_.fetch_add(size));
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700765
766 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700767 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700768 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700769 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700770
771 // TODO: Update these atomically.
772 RuntimeStats* global_stats = Runtime::Current()->GetStats();
773 ++global_stats->allocated_objects;
774 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700775 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700776
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700777 // This is safe to do since the GC will never free objects which are neither in the allocation
778 // stack or the live bitmap.
779 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700780 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700781 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700782
783 return old_num_bytes_allocated + size;
Carl Shapiro58551df2011-07-24 03:09:51 -0700784}
785
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700786void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700787 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700788 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700789
790 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700791 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700792 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700793 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700794
795 // TODO: Do this concurrently.
796 RuntimeStats* global_stats = Runtime::Current()->GetStats();
797 global_stats->freed_objects += freed_objects;
798 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700799 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700800}
801
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700802inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::AllocSpace* space, size_t alloc_size,
803 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700804 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700805 return NULL;
806 }
807 return space->Alloc(self, alloc_size, bytes_allocated);
808}
809
810// DlMallocSpace-specific version.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700811inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
812 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700813 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700814 return NULL;
815 }
Mathieu Chartier720ef762013-08-17 14:46:54 -0700816 if (LIKELY(!running_on_valgrind_)) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700817 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
818 } else {
819 return space->Alloc(self, alloc_size, bytes_allocated);
820 }
821}
822
823template <class T>
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700824inline mirror::Object* Heap::AllocateInstrumented(Thread* self, T* space, size_t alloc_size,
825 size_t* bytes_allocated) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700826 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
827 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700828 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700829 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700830
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700831 mirror::Object* ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
832 if (LIKELY(ptr != NULL)) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700833 return ptr;
834 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700835 return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
836}
837
Mathieu Chartier720ef762013-08-17 14:46:54 -0700838mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space,
839 size_t alloc_size, size_t* bytes_allocated) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700840 mirror::Object* ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700841
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700842 // The allocation failed. If the GC is running, block until it completes, and then retry the
843 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700844 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
845 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700846 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700847 ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700848 if (ptr != NULL) {
849 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700850 }
851 }
852
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700853 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700854 for (size_t i = static_cast<size_t>(last_gc) + 1;
855 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700856 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700857 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700858 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700859 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700860 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700861 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
862 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700863 break;
864 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700865 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700866 run_gc = have_zygote_space_;
867 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700868 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700869 run_gc = true;
870 break;
871 default:
872 break;
873 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700874
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700875 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700876 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700877 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800878 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700879 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700880
881 // Did we free sufficient memory for the allocation to succeed?
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700882 ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700883 if (ptr != NULL) {
884 return ptr;
885 }
886 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700887 }
888
889 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700890 // Try harder, growing the heap if necessary.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700891 ptr = TryToAllocateInstrumented(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700892 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700893 return ptr;
894 }
895
Elliott Hughes81ff3182012-03-23 20:35:56 -0700896 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
897 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
898 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700899
Elliott Hughes418dfe72011-10-06 18:56:27 -0700900 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700901 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
902 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700903
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700904 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700905 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700906 return TryToAllocateInstrumented(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700907}
908
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700909void Heap::SetTargetHeapUtilization(float target) {
910 DCHECK_GT(target, 0.0f); // asserted in Java code
911 DCHECK_LT(target, 1.0f);
912 target_utilization_ = target;
913}
914
Ian Rogers1d54e732013-05-02 21:10:01 -0700915size_t Heap::GetObjectsAllocated() const {
916 size_t total = 0;
917 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
918 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
919 space::ContinuousSpace* space = *it;
920 if (space->IsDlMallocSpace()) {
921 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700922 }
923 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700924 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
925 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
926 space::DiscontinuousSpace* space = *it;
927 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
928 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700929 return total;
930}
931
Ian Rogers1d54e732013-05-02 21:10:01 -0700932size_t Heap::GetObjectsAllocatedEver() const {
933 size_t total = 0;
934 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
935 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
936 space::ContinuousSpace* space = *it;
937 if (space->IsDlMallocSpace()) {
938 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700939 }
940 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700941 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
942 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
943 space::DiscontinuousSpace* space = *it;
944 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
945 }
946 return total;
947}
948
949size_t Heap::GetBytesAllocatedEver() const {
950 size_t total = 0;
951 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
952 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
953 space::ContinuousSpace* space = *it;
954 if (space->IsDlMallocSpace()) {
955 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
956 }
957 }
958 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
959 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
960 space::DiscontinuousSpace* space = *it;
961 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
962 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700963 return total;
964}
965
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700966class InstanceCounter {
967 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800968 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700969 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800970 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700971 }
972
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800973 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800974 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800975 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800976 if (use_is_assignable_from_) {
977 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
978 ++counts_[i];
979 }
980 } else {
981 if (instance_class == classes_[i]) {
982 ++counts_[i];
983 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700984 }
985 }
986 }
987
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700988 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800989 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800990 bool use_is_assignable_from_;
991 uint64_t* const counts_;
992
993 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700994};
995
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800996void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800997 uint64_t* counts) {
998 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
999 // is empty, so the live bitmap is the only place we need to look.
1000 Thread* self = Thread::Current();
1001 self->TransitionFromRunnableToSuspended(kNative);
1002 CollectGarbage(false);
1003 self->TransitionFromSuspendedToRunnable();
1004
1005 InstanceCounter counter(classes, use_is_assignable_from, counts);
1006 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001007 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001008}
1009
Elliott Hughes3b78c942013-01-15 17:35:41 -08001010class InstanceCollector {
1011 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001012 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001013 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1014 : class_(c), max_count_(max_count), instances_(instances) {
1015 }
1016
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001017 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1018 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001019 if (instance_class == class_) {
1020 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001021 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001022 }
1023 }
1024 }
1025
1026 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001027 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001028 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001029 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001030
1031 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1032};
1033
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001034void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1035 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001036 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1037 // is empty, so the live bitmap is the only place we need to look.
1038 Thread* self = Thread::Current();
1039 self->TransitionFromRunnableToSuspended(kNative);
1040 CollectGarbage(false);
1041 self->TransitionFromSuspendedToRunnable();
1042
1043 InstanceCollector collector(c, max_count, instances);
1044 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1045 GetLiveBitmap()->Visit(collector);
1046}
1047
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001048class ReferringObjectsFinder {
1049 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001050 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1051 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001052 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1053 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1054 }
1055
1056 // For bitmap Visit.
1057 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1058 // annotalysis on visitors.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001059 void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1060 collector::MarkSweep::VisitObjectReferences(obj, *this, true);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001061 }
1062
1063 // For MarkSweep::VisitObjectReferences.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001064 void operator()(mirror::Object* referrer, mirror::Object* object,
Brian Carlstromdf629502013-07-17 22:39:56 -07001065 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001066 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001067 referring_objects_.push_back(referrer);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001068 }
1069 }
1070
1071 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001072 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001073 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001074 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001075
1076 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1077};
1078
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001079void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1080 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001081 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1082 // is empty, so the live bitmap is the only place we need to look.
1083 Thread* self = Thread::Current();
1084 self->TransitionFromRunnableToSuspended(kNative);
1085 CollectGarbage(false);
1086 self->TransitionFromSuspendedToRunnable();
1087
1088 ReferringObjectsFinder finder(o, max_count, referring_objects);
1089 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1090 GetLiveBitmap()->Visit(finder);
1091}
1092
Ian Rogers30fab402012-01-23 15:43:46 -08001093void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001094 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1095 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001096 Thread* self = Thread::Current();
1097 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001098 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001099}
1100
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001101void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001102 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001103 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1104 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001105 Thread* self = Thread::Current();
1106 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001107
1108 // Try to see if we have any Zygote spaces.
1109 if (have_zygote_space_) {
1110 return;
1111 }
1112
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001113 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1114
1115 {
1116 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001117 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001118 FlushAllocStack();
1119 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001120
Ian Rogers1d54e732013-05-02 21:10:01 -07001121 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1122 // of the remaining available heap memory.
1123 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001124 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -07001125 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001126
Ian Rogers1d54e732013-05-02 21:10:01 -07001127 // Change the GC retention policy of the zygote space to only collect when full.
1128 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1129 AddContinuousSpace(alloc_space_);
1130 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001131
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001132 // Create the zygote space mod union table.
1133 accounting::ModUnionTable* mod_union_table =
1134 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1135 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1136 AddModUnionTable(mod_union_table);
1137
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001138 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001139 for (const auto& collector : mark_sweep_collectors_) {
1140 collector->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001141 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001142}
1143
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001144void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001145 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1146 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001147 allocation_stack_->Reset();
1148}
1149
Ian Rogers1d54e732013-05-02 21:10:01 -07001150void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1151 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001152 mirror::Object** limit = stack->End();
1153 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1154 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001155 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001156 if (LIKELY(bitmap->HasAddress(obj))) {
1157 bitmap->Set(obj);
1158 } else {
1159 large_objects->Set(obj);
1160 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001161 }
1162}
1163
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001164
1165const char* gc_cause_and_type_strings[3][4] = {
1166 {"", "GC Alloc Sticky", "GC Alloc Partial", "GC Alloc Full"},
1167 {"", "GC Background Sticky", "GC Background Partial", "GC Background Full"},
1168 {"", "GC Explicit Sticky", "GC Explicit Partial", "GC Explicit Full"}};
1169
Ian Rogers1d54e732013-05-02 21:10:01 -07001170collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1171 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001172 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001173
Mathieu Chartier65db8802012-11-20 12:36:46 -08001174 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001175 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001176
Ian Rogers120f1c72012-09-28 17:17:10 -07001177 if (self->IsHandlingStackOverflow()) {
1178 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1179 }
1180
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001181 // Ensure there is only one GC at a time.
1182 bool start_collect = false;
1183 while (!start_collect) {
1184 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001185 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001186 if (!is_gc_running_) {
1187 is_gc_running_ = true;
1188 start_collect = true;
1189 }
1190 }
1191 if (!start_collect) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001192 // TODO: timinglog this.
Ian Rogers81d425b2012-09-27 16:03:43 -07001193 WaitForConcurrentGcToComplete(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001194
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001195 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1196 // Not doing at the moment to ensure soft references are cleared.
1197 }
1198 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001199 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001200
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001201 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1202 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1203 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1204 }
1205
Ian Rogers1d54e732013-05-02 21:10:01 -07001206 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001207 uint64_t gc_start_size = GetBytesAllocated();
1208 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001209 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001210 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1211 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001212 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001213 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001214 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001215 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1216 }
1217
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001218 if (gc_type == collector::kGcTypeSticky &&
1219 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1220 gc_type = collector::kGcTypePartial;
1221 }
1222
Ian Rogers1d54e732013-05-02 21:10:01 -07001223 DCHECK_LT(gc_type, collector::kGcTypeMax);
1224 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001225 DCHECK_LE(gc_cause, kGcCauseExplicit);
1226
1227 ATRACE_BEGIN(gc_cause_and_type_strings[gc_cause][gc_type]);
1228
Ian Rogers1d54e732013-05-02 21:10:01 -07001229 collector::MarkSweep* collector = NULL;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001230 for (const auto& cur_collector : mark_sweep_collectors_) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001231 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1232 collector = cur_collector;
1233 break;
1234 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001235 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001236 CHECK(collector != NULL)
1237 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1238 << " and type=" << gc_type;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001239
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001240 collector->clear_soft_references_ = clear_soft_references;
1241 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001242 total_objects_freed_ever_ += collector->GetFreedObjects();
1243 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001244 if (care_about_pause_times_) {
1245 const size_t duration = collector->GetDurationNs();
1246 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1247 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001248 bool was_slow = duration > long_gc_log_threshold_ ||
1249 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001250 if (!was_slow) {
1251 for (uint64_t pause : pauses) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001252 was_slow = was_slow || pause > long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001253 }
1254 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001255
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001256 if (was_slow) {
1257 const size_t percent_free = GetPercentFree();
1258 const size_t current_heap_size = GetBytesAllocated();
1259 const size_t total_memory = GetTotalMemory();
1260 std::ostringstream pause_string;
1261 for (size_t i = 0; i < pauses.size(); ++i) {
1262 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1263 << ((i != pauses.size() - 1) ? ", " : "");
1264 }
1265 LOG(INFO) << gc_cause << " " << collector->GetName()
1266 << " GC freed " << collector->GetFreedObjects() << "("
1267 << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1268 << collector->GetFreedLargeObjects() << "("
1269 << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1270 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1271 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1272 << " total " << PrettyDuration((duration / 1000) * 1000);
1273 if (VLOG_IS_ON(heap)) {
1274 LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
1275 }
1276 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001277 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001278
Ian Rogers15bf2d32012-08-28 17:33:04 -07001279 {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001280 MutexLock mu(self, *gc_complete_lock_);
1281 is_gc_running_ = false;
1282 last_gc_type_ = gc_type;
1283 // Wake anyone who may have been waiting for the GC to complete.
1284 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001285 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001286
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001287 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001288
1289 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001290 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001291 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001292}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001293
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001294static mirror::Object* RootMatchesObjectVisitor(mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001295 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001296 if (root == obj) {
1297 LOG(INFO) << "Object " << obj << " is a root";
1298 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001299 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001300}
1301
1302class ScanVisitor {
1303 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001304 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001305 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001306 }
1307};
1308
Ian Rogers1d54e732013-05-02 21:10:01 -07001309// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001310class VerifyReferenceVisitor {
1311 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001312 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001313 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001314 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001315
1316 bool Failed() const {
1317 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001318 }
1319
1320 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001321 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001322 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1323 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001324 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001325 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001326 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1327 accounting::CardTable* card_table = heap_->GetCardTable();
1328 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1329 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001330
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001331 if (!failed_) {
1332 // Print message on only on first failure to prevent spam.
1333 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
1334 failed_ = true;
1335 }
1336 if (obj != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001337 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001338 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
1339 << offset << "\n card value = " << static_cast<int>(*card_addr);
1340 if (heap_->IsHeapAddress(obj->GetClass())) {
1341 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1342 } else {
1343 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
1344 }
1345
1346 // Attmept to find the class inside of the recently freed objects.
1347 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
1348 if (ref_space->IsDlMallocSpace()) {
1349 space::DlMallocSpace* space = ref_space->AsDlMallocSpace();
1350 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
1351 if (ref_class != nullptr) {
1352 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
1353 << PrettyClass(ref_class);
1354 } else {
1355 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
1356 }
1357 }
1358
1359 if (ref->GetClass() != nullptr && heap_->IsHeapAddress(ref->GetClass()) &&
1360 ref->GetClass()->IsClass()) {
1361 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1362 } else {
1363 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
1364 << ") is not a valid heap address";
1365 }
1366
Ian Rogers1d54e732013-05-02 21:10:01 -07001367 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1368 void* cover_begin = card_table->AddrFromCard(card_addr);
1369 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1370 accounting::CardTable::kCardSize);
1371 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1372 << "-" << cover_end;
1373 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001374
Ian Rogers1d54e732013-05-02 21:10:01 -07001375 // Print out how the object is live.
1376 if (bitmap != NULL && bitmap->Test(obj)) {
1377 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1378 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001379 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001380 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1381 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001382 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001383 LOG(ERROR) << "Object " << obj << " found in live stack";
1384 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001385 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1386 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
1387 }
1388 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1389 LOG(ERROR) << "Ref " << ref << " found in live stack";
1390 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001391 // Attempt to see if the card table missed the reference.
1392 ScanVisitor scan_visitor;
1393 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1394 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001395 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001396
1397 // Search to see if any of the roots reference our object.
1398 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1399 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1400
1401 // Search to see if any of the roots reference our reference.
1402 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1403 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1404 } else {
1405 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001406 }
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 {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001411 return heap_->IsLiveObjectLocked(obj, true, false, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001412 }
1413
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001414 static mirror::Object* VerifyRoots(mirror::Object* root, void* arg) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001415 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001416 (*visitor)(nullptr, root, MemberOffset(0), true);
1417 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001418 }
1419
1420 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001421 Heap* const heap_;
1422 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001423};
1424
Ian Rogers1d54e732013-05-02 21:10:01 -07001425// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001426class VerifyObjectVisitor {
1427 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001428 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001429
Brian Carlstromdf629502013-07-17 22:39:56 -07001430 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001431 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001432 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1433 // be live or else how did we find it in the live bitmap?
1434 VerifyReferenceVisitor visitor(heap_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001435 // The class doesn't count as a reference but we should verify it anyways.
1436 visitor(obj, obj->GetClass(), MemberOffset(0), false);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001437 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(obj), visitor, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001438 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001439 }
1440
1441 bool Failed() const {
1442 return failed_;
1443 }
1444
1445 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001446 Heap* const heap_;
1447 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001448};
1449
1450// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001451bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001452 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001453 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001454 allocation_stack_->Sort();
1455 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001456 // Perform the verification.
1457 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001458 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001459 GetLiveBitmap()->Visit(visitor);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001460 // Verify objects in the allocation stack since these will be objects which were:
1461 // 1. Allocated prior to the GC (pre GC verification).
1462 // 2. Allocated during the GC (pre sweep GC verification).
1463 for (mirror::Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
1464 visitor(*it);
1465 }
1466 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001467 // pointing to dead objects if they are not reachable.
1468 if (visitor.Failed()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001469 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001470 for (const auto& table_pair : mod_union_tables_) {
1471 accounting::ModUnionTable* mod_union_table = table_pair.second;
1472 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
1473 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001474 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001475 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001476 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001477 return true;
1478}
1479
1480class VerifyReferenceCardVisitor {
1481 public:
1482 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1483 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1484 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001485 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001486 }
1487
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001488 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1489 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001490 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1491 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001492 // Filter out class references since changing an object's class does not mark the card as dirty.
1493 // Also handles large objects, since the only reference they hold is a class reference.
1494 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001495 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001496 // If the object is not dirty and it is referencing something in the live stack other than
1497 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001498 if (!card_table->AddrIsInCardTable(obj)) {
1499 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1500 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001501 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001502 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1503 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001504 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001505 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1506 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001507 LOG(ERROR) << "Object " << obj << " found in live stack";
1508 }
1509 if (heap_->GetLiveBitmap()->Test(obj)) {
1510 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1511 }
1512 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1513 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1514
1515 // Print which field of the object is dead.
1516 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001517 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001518 CHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001519 const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
1520 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001521 CHECK(fields != NULL);
1522 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001523 const mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001524 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1525 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1526 << PrettyField(cur);
1527 break;
1528 }
1529 }
1530 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001531 const mirror::ObjectArray<mirror::Object>* object_array =
1532 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001533 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1534 if (object_array->Get(i) == ref) {
1535 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1536 }
1537 }
1538 }
1539
1540 *failed_ = true;
1541 }
1542 }
1543 }
1544 }
1545
1546 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001547 Heap* const heap_;
1548 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001549};
1550
1551class VerifyLiveStackReferences {
1552 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001553 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001554 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001555 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001556
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001557 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001558 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1559 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001560 collector::MarkSweep::VisitObjectReferences(obj, visitor, true);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001561 }
1562
1563 bool Failed() const {
1564 return failed_;
1565 }
1566
1567 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001568 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001569 bool failed_;
1570};
1571
1572bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001573 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001574
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001575 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001576 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001577 VerifyLiveStackReferences visitor(this);
1578 GetLiveBitmap()->Visit(visitor);
1579
1580 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001581 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001582 visitor(*it);
1583 }
1584
1585 if (visitor.Failed()) {
1586 DumpSpaces();
1587 return false;
1588 }
1589 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001590}
1591
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001592void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001593 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001594}
1595
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001596accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
1597 auto it = mod_union_tables_.find(space);
1598 if (it == mod_union_tables_.end()) {
1599 return nullptr;
1600 }
1601 return it->second;
1602}
1603
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001604void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001605 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001606 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001607 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
1608 if (table != nullptr) {
1609 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
1610 "ImageModUnionClearCards";
1611 base::TimingLogger::ScopedSplit split(name, &timings);
1612 table->ClearCards();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001613 } else {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001614 base::TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001615 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1616 // were dirty before the GC started.
1617 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001618 }
1619 }
1620}
1621
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001622static mirror::Object* IdentityCallback(mirror::Object* obj, void*) {
1623 return obj;
1624}
1625
Ian Rogers1d54e732013-05-02 21:10:01 -07001626void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001627 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1628 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001629
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001630 if (verify_pre_gc_heap_) {
1631 thread_list->SuspendAll();
1632 {
1633 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1634 if (!VerifyHeapReferences()) {
1635 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1636 }
1637 }
1638 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001639 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001640
1641 // Check that all objects which reference things in the live stack are on dirty cards.
1642 if (verify_missing_card_marks_) {
1643 thread_list->SuspendAll();
1644 {
1645 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1646 SwapStacks();
1647 // Sort the live stack so that we can quickly binary search it later.
1648 if (!VerifyMissingCardMarks()) {
1649 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1650 }
1651 SwapStacks();
1652 }
1653 thread_list->ResumeAll();
1654 }
1655
1656 if (verify_mod_union_table_) {
1657 thread_list->SuspendAll();
1658 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001659 for (const auto& table_pair : mod_union_tables_) {
1660 accounting::ModUnionTable* mod_union_table = table_pair.second;
1661 mod_union_table->UpdateAndMarkReferences(IdentityCallback, nullptr);
1662 mod_union_table->Verify();
1663 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001664 thread_list->ResumeAll();
1665 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001666}
1667
Ian Rogers1d54e732013-05-02 21:10:01 -07001668void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001669 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1670 // reachable objects.
1671 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001672 Thread* self = Thread::Current();
1673 CHECK_NE(self->GetState(), kRunnable);
Ian Rogers1d54e732013-05-02 21:10:01 -07001674 {
1675 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1676 // Swapping bound bitmaps does nothing.
1677 gc->SwapBitmaps();
1678 if (!VerifyHeapReferences()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001679 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
Ian Rogers1d54e732013-05-02 21:10:01 -07001680 }
1681 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001682 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001683 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001684}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001685
Ian Rogers1d54e732013-05-02 21:10:01 -07001686void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001687 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001688 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001689 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001690 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001691 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001692 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001693}
1694
Ian Rogers1d54e732013-05-02 21:10:01 -07001695collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1696 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001697 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001698 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001699 bool do_wait;
1700 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001701 {
1702 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001703 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001704 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001705 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001706 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001707 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001708 // We must wait, change thread state then sleep on gc_complete_cond_;
1709 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1710 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001711 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001712 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001713 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001714 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001715 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001716 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001717 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001718 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001719 if (wait_time > long_pause_log_threshold_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001720 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1721 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001722 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001723 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001724 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001725 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001726}
1727
Elliott Hughesc967f782012-04-16 10:23:15 -07001728void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001729 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001730 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001731 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001732}
1733
1734size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001735 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001736}
1737
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001738void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001739 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001740 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001741 << PrettySize(GetMaxMemory());
1742 max_allowed_footprint = GetMaxMemory();
1743 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001744 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001745}
1746
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001747void Heap::UpdateMaxNativeFootprint() {
1748 size_t native_size = native_bytes_allocated_;
1749 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1750 size_t target_size = native_size / GetTargetHeapUtilization();
1751 if (target_size > native_size + max_free_) {
1752 target_size = native_size + max_free_;
1753 } else if (target_size < native_size + min_free_) {
1754 target_size = native_size + min_free_;
1755 }
1756 native_footprint_gc_watermark_ = target_size;
1757 native_footprint_limit_ = 2 * target_size - native_size;
1758}
1759
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001760void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001761 // We know what our utilization is at this moment.
1762 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001763 const size_t bytes_allocated = GetBytesAllocated();
1764 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001765 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001766
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001767 size_t target_size;
1768 if (gc_type != collector::kGcTypeSticky) {
1769 // Grow the heap for non sticky GC.
1770 target_size = bytes_allocated / GetTargetHeapUtilization();
1771 if (target_size > bytes_allocated + max_free_) {
1772 target_size = bytes_allocated + max_free_;
1773 } else if (target_size < bytes_allocated + min_free_) {
1774 target_size = bytes_allocated + min_free_;
1775 }
1776 next_gc_type_ = collector::kGcTypeSticky;
1777 } else {
1778 // Based on how close the current heap size is to the target size, decide
1779 // whether or not to do a partial or sticky GC next.
1780 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1781 next_gc_type_ = collector::kGcTypeSticky;
1782 } else {
1783 next_gc_type_ = collector::kGcTypePartial;
1784 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001785
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001786 // If we have freed enough memory, shrink the heap back down.
1787 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1788 target_size = bytes_allocated + max_free_;
1789 } else {
1790 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1791 }
1792 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001793
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001794 if (!ignore_max_footprint_) {
1795 SetIdealFootprint(target_size);
1796
1797 if (concurrent_gc_) {
1798 // Calculate when to perform the next ConcurrentGC.
1799
1800 // Calculate the estimated GC duration.
1801 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1802 // Estimate how many remaining bytes we will have when we need to start the next GC.
1803 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1804 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1805 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1806 // A never going to happen situation that from the estimated allocation rate we will exceed
1807 // the applications entire footprint with the given estimated allocation rate. Schedule
1808 // another GC straight away.
1809 concurrent_start_bytes_ = bytes_allocated;
1810 } else {
1811 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1812 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1813 // right away.
1814 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1815 }
1816 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1817 DCHECK_LE(max_allowed_footprint_, growth_limit_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001818 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001819 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001820
1821 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001822}
1823
jeffhaoc1160702011-10-27 15:48:45 -07001824void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001825 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001826 alloc_space_->ClearGrowthLimit();
1827}
1828
Elliott Hughesadb460d2011-10-05 17:02:34 -07001829void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001830 MemberOffset reference_queue_offset,
1831 MemberOffset reference_queueNext_offset,
1832 MemberOffset reference_pendingNext_offset,
1833 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001834 reference_referent_offset_ = reference_referent_offset;
1835 reference_queue_offset_ = reference_queue_offset;
1836 reference_queueNext_offset_ = reference_queueNext_offset;
1837 reference_pendingNext_offset_ = reference_pendingNext_offset;
1838 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1839 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1840 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1841 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1842 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1843 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1844}
1845
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001846mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001847 DCHECK(reference != NULL);
1848 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001849 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001850}
1851
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001852void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001853 DCHECK(reference != NULL);
1854 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1855 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1856}
1857
1858// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001859bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001860 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001861 const mirror::Object* queue =
1862 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1863 const mirror::Object* queue_next =
1864 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001865 return (queue != NULL) && (queue_next == NULL);
1866}
1867
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001868void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001869 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001870 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1871 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001872 EnqueuePendingReference(ref, cleared_reference_list);
1873}
1874
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001875bool Heap::IsEnqueued(mirror::Object* ref) {
1876 // Since the references are stored as cyclic lists it means that once enqueued, the pending next
1877 // will always be non-null.
1878 return ref->GetFieldObject<mirror::Object*>(GetReferencePendingNextOffset(), false) != nullptr;
1879}
1880
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001881void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001882 DCHECK(ref != NULL);
1883 DCHECK(list != NULL);
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001884 if (*list == NULL) {
1885 // 1 element cyclic queue, ie: Reference ref = ..; ref.pendingNext = ref;
1886 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1887 *list = ref;
1888 } else {
1889 mirror::Object* head =
1890 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
1891 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1892 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001893 }
1894}
1895
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001896mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001897 DCHECK(list != NULL);
1898 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001899 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1900 false);
1901 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001902
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001903 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1904 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001905 if (*list == head) {
1906 ref = *list;
1907 *list = NULL;
1908 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001909 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1910 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001911 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1912 ref = head;
1913 }
1914 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1915 return ref;
1916}
1917
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001918void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001919 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001920 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001921 ArgArray arg_array(NULL, 0);
1922 arg_array.Append(reinterpret_cast<uint32_t>(object));
1923 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001924 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001925}
1926
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001927void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001928 DCHECK(cleared != NULL);
1929 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001930 // When a runtime isn't started there are no reference queues to care about so ignore.
1931 if (LIKELY(Runtime::Current()->IsStarted())) {
1932 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001933 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001934 ArgArray arg_array(NULL, 0);
1935 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1936 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001937 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001938 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001939 *cleared = NULL;
1940 }
1941}
1942
Ian Rogers1f539342012-10-03 21:09:42 -07001943void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001944 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001945 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001946 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001947 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001948 !runtime->IsConcurrentGcEnabled()) {
1949 return;
1950 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001951 {
1952 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1953 if (runtime->IsShuttingDown()) {
1954 return;
1955 }
1956 }
1957 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001958 return;
1959 }
1960
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001961 // We already have a request pending, no reason to start more until we update
1962 // concurrent_start_bytes_.
1963 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1964
Ian Rogers120f1c72012-09-28 17:17:10 -07001965 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001966 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1967 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001968 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1969 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001970 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001971}
1972
Ian Rogers81d425b2012-09-27 16:03:43 -07001973void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001974 {
1975 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001976 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001977 return;
1978 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001979 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001980
Mathieu Chartier65db8802012-11-20 12:36:46 -08001981 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001982 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001983 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001984 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001985}
1986
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001987void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001988 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1989 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1990 // a space it will hold its lock and can become a cause of jank.
1991 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1992 // forking.
1993
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001994 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1995 // because that only marks object heads, so a large array looks like lots of empty space. We
1996 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1997 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1998 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1999 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08002000 uint64_t ms_time = MilliTime();
Hiroshi Yamauchibe031ff2013-10-08 16:42:37 -07002001 // Note the large object space's bytes allocated is equal to its capacity.
2002 uint64_t los_bytes_allocated = large_object_space_->GetBytesAllocated();
2003 float utilization = static_cast<float>(GetBytesAllocated() - los_bytes_allocated) /
2004 (GetTotalMemory() - los_bytes_allocated);
Mathieu Chartiere0a53e92013-08-05 10:17:40 -07002005 if ((utilization > 0.75f && !IsLowMemoryMode()) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
2006 // Don't bother trimming the alloc space if it's more than 75% utilized and low memory mode is
2007 // not enabled, or if a heap trim occurred in the last two seconds.
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002008 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002009 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002010
2011 Thread* self = Thread::Current();
2012 {
2013 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2014 Runtime* runtime = Runtime::Current();
2015 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2016 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2017 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2018 // as we don't hold the lock while requesting the trim).
2019 return;
2020 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002021 }
Ian Rogers48931882013-01-22 14:35:16 -08002022
Ian Rogers1d54e732013-05-02 21:10:01 -07002023 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002024 ListenForProcessStateChange();
2025
2026 // Trim only if we do not currently care about pause times.
2027 if (!care_about_pause_times_) {
2028 JNIEnv* env = self->GetJniEnv();
2029 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2030 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2031 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2032 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2033 CHECK(!env->ExceptionCheck());
2034 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002035}
2036
Ian Rogers48931882013-01-22 14:35:16 -08002037size_t Heap::Trim() {
2038 // Handle a requested heap trim on a thread outside of the main GC thread.
2039 return alloc_space_->Trim();
2040}
2041
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002042bool Heap::IsGCRequestPending() const {
2043 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2044}
2045
Ian Rogers1eb512d2013-10-18 15:42:20 -07002046void Heap::RegisterNativeAllocation(JNIEnv* env, int bytes) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002047 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002048 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002049 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
2050 // The second watermark is higher than the gc watermark. If you hit this it means you are
2051 // allocating native objects faster than the GC can keep up with.
2052 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002053 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
2054 // point.
Ian Rogers1eb512d2013-10-18 15:42:20 -07002055 if (UNLIKELY(WellKnownClasses::java_lang_System_runFinalization == NULL)) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002056 DCHECK(WellKnownClasses::java_lang_System != NULL);
2057 WellKnownClasses::java_lang_System_runFinalization =
2058 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
Ian Rogers1eb512d2013-10-18 15:42:20 -07002059 CHECK(WellKnownClasses::java_lang_System_runFinalization != NULL);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002060 }
Ian Rogers1eb512d2013-10-18 15:42:20 -07002061 if (WaitForConcurrentGcToComplete(ThreadForEnv(env)) != collector::kGcTypeNone) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002062 // Just finished a GC, attempt to run finalizers.
2063 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2064 WellKnownClasses::java_lang_System_runFinalization);
2065 CHECK(!env->ExceptionCheck());
2066 }
2067
2068 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2069 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2070 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
2071 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2072 WellKnownClasses::java_lang_System_runFinalization);
2073 CHECK(!env->ExceptionCheck());
2074 }
2075 // We have just run finalizers, update the native watermark since it is very likely that
2076 // finalizers released native managed allocations.
2077 UpdateMaxNativeFootprint();
2078 } else {
2079 if (!IsGCRequestPending()) {
Ian Rogers1eb512d2013-10-18 15:42:20 -07002080 RequestConcurrentGC(ThreadForEnv(env));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002081 }
2082 }
2083 }
2084}
2085
Ian Rogers1eb512d2013-10-18 15:42:20 -07002086void Heap::RegisterNativeFree(JNIEnv* env, int bytes) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002087 int expected_size, new_size;
2088 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002089 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002090 new_size = expected_size - bytes;
Ian Rogers1eb512d2013-10-18 15:42:20 -07002091 if (UNLIKELY(new_size < 0)) {
2092 ScopedObjectAccess soa(env);
2093 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
2094 StringPrintf("Attempted to free %d native bytes with only %d native bytes "
2095 "registered as allocated", bytes, expected_size).c_str());
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002096 break;
2097 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002098 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002099}
2100
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002101int64_t Heap::GetTotalMemory() const {
2102 int64_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002103 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002104 if (space->IsImageSpace()) {
2105 // Currently don't include the image space.
2106 } else if (space->IsDlMallocSpace()) {
2107 // Zygote or alloc space
2108 ret += space->AsDlMallocSpace()->GetFootprint();
2109 }
2110 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002111 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002112 if (space->IsLargeObjectSpace()) {
2113 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2114 }
2115 }
2116 return ret;
2117}
2118
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002119void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
2120 DCHECK(mod_union_table != nullptr);
2121 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
2122}
2123
Ian Rogers1d54e732013-05-02 21:10:01 -07002124} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002125} // namespace art