blob: c0e46ac1658914d7d68f9e1d2841966efd9d691b [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,
Mathieu Chartiere0a53e92013-08-05 10:17:40 -070069 double target_utilization, size_t capacity, const std::string& original_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 std::string image_file_name(original_image_file_name);
148 if (!image_file_name.empty()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700149 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
150 CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700151 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800152 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
153 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800154 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
155 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700156 if (oat_file_end_addr > requested_alloc_space_begin) {
157 requested_alloc_space_begin =
158 reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
159 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700160 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700161 }
162
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -0700163 alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
Ian Rogers1d54e732013-05-02 21:10:01 -0700164 initial_size,
165 growth_limit, capacity,
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700166 requested_alloc_space_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700167 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700168 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700169 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700170
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700171 // Allocate the large object space.
172 const bool kUseFreeListSpaceForLOS = false;
173 if (kUseFreeListSpaceForLOS) {
174 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
175 } else {
176 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
177 }
178 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
179 AddDiscontinuousSpace(large_object_space_);
180
Ian Rogers1d54e732013-05-02 21:10:01 -0700181 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
182 byte* heap_begin = continuous_spaces_.front()->Begin();
183 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
184 if (continuous_spaces_.back()->IsDlMallocSpace()) {
185 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700186 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700187
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800188 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700189 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700190 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700191
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700192 accounting::ModUnionTable* mod_union_table =
193 new accounting::ModUnionTableToZygoteAllocspace("Image mod-union table", this,
194 GetImageSpace());
195 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
196 AddModUnionTable(mod_union_table);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700197
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700198 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700199 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700200
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800201 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700202 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700203 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
204 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
205 max_allocation_stack_size_));
206 live_stack_.reset(accounting::ObjectStack::Create("live stack",
207 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700208
Mathieu Chartier65db8802012-11-20 12:36:46 -0800209 // It's still too early to take a lock because there are no threads yet, but we can create locks
210 // now. We don't create it earlier to make it clear that you can't use locks during heap
211 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700212 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700213 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
214 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700215
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700216 // Create the reference queue locks, this is required so for parallel object scanning in the GC.
217 soft_ref_queue_lock_ = new Mutex("Soft reference queue lock");
218 weak_ref_queue_lock_ = new Mutex("Weak reference queue lock");
219 finalizer_ref_queue_lock_ = new Mutex("Finalizer reference queue lock");
220 phantom_ref_queue_lock_ = new Mutex("Phantom reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700221
Ian Rogers1d54e732013-05-02 21:10:01 -0700222 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800223 last_gc_size_ = GetBytesAllocated();
224
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700225 if (ignore_max_footprint_) {
226 SetIdealFootprint(std::numeric_limits<size_t>::max());
227 concurrent_start_bytes_ = max_allowed_footprint_;
228 }
229
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800230 // Create our garbage collectors.
231 for (size_t i = 0; i < 2; ++i) {
232 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700233 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
234 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
235 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700236 }
237
Brian Carlstrom42748892013-07-18 18:04:08 -0700238 CHECK_NE(max_allowed_footprint_, 0U);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700239
240 if (running_on_valgrind_) {
241 Runtime::Current()->InstrumentQuickAllocEntryPoints();
242 }
243
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800244 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800245 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700246 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700247}
248
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700249void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700250 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
251 if (num_threads != 0) {
252 thread_pool_.reset(new ThreadPool(num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700253 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700254}
255
256void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700257 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700258}
259
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700260static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
261 CHECK(out_value != NULL);
262 jfieldID field = env->GetStaticFieldID(clz, name, "I");
263 if (field == NULL) {
264 env->ExceptionClear();
265 return false;
266 }
267 *out_value = env->GetStaticIntField(clz, field);
268 return true;
269}
270
271void Heap::ListenForProcessStateChange() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700272 VLOG(heap) << "Heap notified of process state change";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700273
274 Thread* self = Thread::Current();
275 JNIEnvExt* env = self->GetJniEnv();
276
277 if (!have_zygote_space_) {
278 return;
279 }
280
281 if (activity_thread_class_ == NULL) {
282 jclass clz = env->FindClass("android/app/ActivityThread");
283 if (clz == NULL) {
284 env->ExceptionClear();
285 LOG(WARNING) << "Could not find activity thread class in process state change";
286 return;
287 }
288 activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
289 }
290
291 if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
292 jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
293 "currentActivityThread",
294 "()Landroid/app/ActivityThread;");
295 if (current_activity_method == NULL) {
296 env->ExceptionClear();
297 LOG(WARNING) << "Could not get method for currentActivityThread";
298 return;
299 }
300
301 jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
302 if (obj == NULL) {
303 env->ExceptionClear();
304 LOG(WARNING) << "Could not get current activity";
305 return;
306 }
307 activity_thread_ = env->NewGlobalRef(obj);
308 }
309
310 if (process_state_cares_about_pause_time_.empty()) {
311 // Just attempt to do this the first time.
312 jclass clz = env->FindClass("android/app/ActivityManager");
313 if (clz == NULL) {
314 LOG(WARNING) << "Activity manager class is null";
315 return;
316 }
317 ScopedLocalRef<jclass> activity_manager(env, clz);
318 std::vector<const char*> care_about_pauses;
319 care_about_pauses.push_back("PROCESS_STATE_TOP");
320 care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
321 // Attempt to read the constants and classify them as whether or not we care about pause times.
322 for (size_t i = 0; i < care_about_pauses.size(); ++i) {
323 int process_state = 0;
324 if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
325 process_state_cares_about_pause_time_.insert(process_state);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700326 VLOG(heap) << "Adding process state " << process_state
327 << " to set of states which care about pause time";
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700328 }
329 }
330 }
331
332 if (application_thread_class_ == NULL) {
333 jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
334 if (clz == NULL) {
335 env->ExceptionClear();
336 LOG(WARNING) << "Could not get application thread class";
337 return;
338 }
339 application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
340 last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
341 if (last_process_state_id_ == NULL) {
342 env->ExceptionClear();
343 LOG(WARNING) << "Could not get last process state member";
344 return;
345 }
346 }
347
348 if (application_thread_class_ != NULL && application_thread_ == NULL) {
349 jmethodID get_application_thread =
350 env->GetMethodID(activity_thread_class_, "getApplicationThread",
351 "()Landroid/app/ActivityThread$ApplicationThread;");
352 if (get_application_thread == NULL) {
353 LOG(WARNING) << "Could not get method ID for get application thread";
354 return;
355 }
356
357 jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
358 if (obj == NULL) {
359 LOG(WARNING) << "Could not get application thread";
360 return;
361 }
362
363 application_thread_ = env->NewGlobalRef(obj);
364 }
365
366 if (application_thread_ != NULL && last_process_state_id_ != NULL) {
367 int process_state = env->GetIntField(application_thread_, last_process_state_id_);
368 env->ExceptionClear();
369
370 care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
371 process_state_cares_about_pause_time_.end();
372
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700373 VLOG(heap) << "New process state " << process_state
374 << " care about pauses " << care_about_pause_times_;
Mathieu Chartierc39e3422013-08-07 16:41:36 -0700375 }
Mathieu Chartier82353312013-07-18 10:47:51 -0700376}
377
Ian Rogers1d54e732013-05-02 21:10:01 -0700378void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700379 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700380 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700381 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700382 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700383 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700384 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
385 continuous_spaces_.push_back(space);
386 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
387 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700388 }
389
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700390 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700391 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
392 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
393 return a->Begin() < b->Begin();
394 });
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700395
396 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
397 // avoid redundant marking.
398 bool seen_zygote = false, seen_alloc = false;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700399 for (const auto& space : continuous_spaces_) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700400 if (space->IsImageSpace()) {
401 DCHECK(!seen_zygote);
402 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700403 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700404 DCHECK(!seen_alloc);
405 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700406 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700407 seen_alloc = true;
408 }
409 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800410}
411
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700412void Heap::RegisterGCAllocation(size_t bytes) {
413 if (this != NULL) {
414 gc_memory_overhead_.fetch_add(bytes);
415 }
416}
417
418void Heap::RegisterGCDeAllocation(size_t bytes) {
419 if (this != NULL) {
420 gc_memory_overhead_.fetch_sub(bytes);
421 }
422}
423
Ian Rogers1d54e732013-05-02 21:10:01 -0700424void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
425 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
426 DCHECK(space != NULL);
427 DCHECK(space->GetLiveObjects() != NULL);
428 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
429 DCHECK(space->GetMarkObjects() != NULL);
430 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
431 discontinuous_spaces_.push_back(space);
432}
433
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700434void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700435 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700436 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700437 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800438
439 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800440 uint64_t total_paused_time = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700441 for (const auto& collector : mark_sweep_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800442 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800443 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700444 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800445 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700446 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800447 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
448 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
449 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700450 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
451 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
452 << collector->GetName() << " freed: " << freed_objects
453 << " objects with total size " << PrettySize(freed_bytes) << "\n"
454 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
455 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800456 total_duration += total_ns;
457 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700458 }
459 }
460 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700461 size_t total_objects_allocated = GetObjectsAllocatedEver();
462 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700463 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700464 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700465 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
466 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700467 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700468 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700469 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700470 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700471 os << "Total number of allocations: " << total_objects_allocated << "\n";
472 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700473 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700474 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
475 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
476 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700477 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700478 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
479 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700480 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700481}
482
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800483Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700484 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700485 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700486 }
487
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800488 STLDeleteElements(&mark_sweep_collectors_);
489
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700490 // If we don't reset then the mark stack complains in it's destructor.
491 allocation_stack_->Reset();
492 live_stack_->Reset();
493
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800494 VLOG(heap) << "~Heap()";
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700495 STLDeleteValues(&mod_union_tables_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700496 STLDeleteElements(&continuous_spaces_);
497 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498 delete gc_complete_lock_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700499 delete soft_ref_queue_lock_;
500 delete weak_ref_queue_lock_;
501 delete finalizer_ref_queue_lock_;
502 delete phantom_ref_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700503}
504
Ian Rogers1d54e732013-05-02 21:10:01 -0700505space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
506 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700507 for (const auto& space : continuous_spaces_) {
508 if (space->Contains(obj)) {
509 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700510 }
511 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700512 if (!fail_ok) {
513 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
514 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700515 return NULL;
516}
517
Ian Rogers1d54e732013-05-02 21:10:01 -0700518space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
519 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700520 for (const auto& space : discontinuous_spaces_) {
521 if (space->Contains(obj)) {
522 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700523 }
524 }
525 if (!fail_ok) {
526 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
527 }
528 return NULL;
529}
530
531space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
532 space::Space* result = FindContinuousSpaceFromObject(obj, true);
533 if (result != NULL) {
534 return result;
535 }
536 return FindDiscontinuousSpaceFromObject(obj, true);
537}
538
539space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700540 for (const auto& space : continuous_spaces_) {
541 if (space->IsImageSpace()) {
542 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700543 }
544 }
545 return NULL;
546}
547
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700548static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700549 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700550 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700551 size_t chunk_free_bytes = chunk_size - used_bytes;
552 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
553 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700554 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700555}
556
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700557void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, bool large_object_allocation) {
558 std::ostringstream oss;
559 int64_t total_bytes_free = GetFreeMemory();
560 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
561 << " free bytes";
562 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
563 if (!large_object_allocation && total_bytes_free >= byte_count) {
564 size_t max_contiguous_allocation = 0;
565 for (const auto& space : continuous_spaces_) {
566 if (space->IsDlMallocSpace()) {
567 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
568 }
569 }
570 oss << "; failed due to fragmentation (largest possible contiguous allocation "
571 << max_contiguous_allocation << " bytes)";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700572 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700573 self->ThrowOutOfMemoryError(oss.str().c_str());
574}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700575
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700576inline bool Heap::TryAllocLargeObjectInstrumented(Thread* self, mirror::Class* c, size_t byte_count,
577 mirror::Object** obj_ptr, size_t* bytes_allocated) {
578 bool large_object_allocation = ShouldAllocLargeObject(c, byte_count);
Ian Rogers333cf1b2013-07-24 11:57:02 -0700579 if (UNLIKELY(large_object_allocation)) {
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700580 mirror::Object* obj = AllocateInstrumented(self, large_object_space_, byte_count, bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700581 // Make sure that our large object didn't get placed anywhere within the space interval or else
582 // it breaks the immune range.
583 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700584 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
585 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700586 *obj_ptr = obj;
587 }
588 return large_object_allocation;
589}
590
591mirror::Object* Heap::AllocObjectInstrumented(Thread* self, mirror::Class* c, size_t byte_count) {
592 DebugCheckPreconditionsForAllobObject(c, byte_count);
593 mirror::Object* obj;
594 size_t bytes_allocated;
595 AllocationTimer alloc_timer(this, &obj);
596 bool large_object_allocation = TryAllocLargeObjectInstrumented(self, c, byte_count,
597 &obj, &bytes_allocated);
598 if (LIKELY(!large_object_allocation)) {
599 // Non-large object allocation.
600 obj = AllocateInstrumented(self, alloc_space_, byte_count, &bytes_allocated);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700601 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700602 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700603 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700604 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700605 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700606 // Record allocation after since we want to use the atomic add for the atomic fence to guard
607 // the SetClass since we do not want the class to appear NULL in another thread.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700608 size_t new_num_bytes_allocated = RecordAllocationInstrumented(bytes_allocated, obj);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700609 if (Dbg::IsAllocTrackingEnabled()) {
610 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700611 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700612 CheckConcurrentGC(self, new_num_bytes_allocated, obj);
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700613 if (kDesiredHeapVerification > kNoHeapVerification) {
614 VerifyObject(obj);
615 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700616 return obj;
Carl Shapiro58551df2011-07-24 03:09:51 -0700617 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700618 ThrowOutOfMemoryError(self, byte_count, large_object_allocation);
619 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700620}
621
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800622bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700623 // Note: we deliberately don't take the lock here, and mustn't test anything that would
624 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700625 if (obj == NULL) {
626 return true;
627 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700628 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700629 return false;
630 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700631 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700632}
633
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700634bool Heap::IsLiveObjectLocked(const mirror::Object* obj, bool search_allocation_stack,
635 bool search_live_stack, bool sorted) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700636 // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700637 if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700638 return false;
639 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700640 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
641 space::DiscontinuousSpace* d_space = NULL;
642 if (c_space != NULL) {
643 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700644 return true;
645 }
646 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700647 d_space = FindDiscontinuousSpaceFromObject(obj, true);
648 if (d_space != NULL) {
649 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700650 return true;
651 }
652 }
653 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700654 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700655 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
656 if (i > 0) {
657 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -0700658 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700659
660 if (search_allocation_stack) {
661 if (sorted) {
662 if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
663 return true;
664 }
665 } else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
666 return true;
667 }
668 }
669
670 if (search_live_stack) {
671 if (sorted) {
672 if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
673 return true;
674 }
675 } else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
676 return true;
677 }
678 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700679 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700680 // We need to check the bitmaps again since there is a race where we mark something as live and
681 // then clear the stack containing it.
682 if (c_space != NULL) {
683 if (c_space->GetLiveBitmap()->Test(obj)) {
684 return true;
685 }
686 } else {
687 d_space = FindDiscontinuousSpaceFromObject(obj, true);
688 if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
689 return true;
690 }
691 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700692 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700693}
694
Ian Rogers04d7aa92013-03-16 14:29:17 -0700695void Heap::VerifyObjectImpl(const mirror::Object* obj) {
696 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700697 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700698 return;
699 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700700 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700701}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700702
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700703void Heap::DumpSpaces() {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700704 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700705 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
706 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700707 LOG(INFO) << space << " " << *space << "\n"
708 << live_bitmap << " " << *live_bitmap << "\n"
709 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700710 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700711 for (const auto& space : discontinuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700712 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700713 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700714}
715
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800716void Heap::VerifyObjectBody(const mirror::Object* obj) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700717 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
718 // Ignore early dawn of the universe verifications.
719 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.load()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800720 return;
721 }
722 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
723 mirror::Object::ClassOffset().Int32Value();
724 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
725 if (UNLIKELY(c == NULL)) {
726 LOG(FATAL) << "Null class in object: " << obj;
727 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
728 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
729 }
730 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
731 // Note: we don't use the accessors here as they have internal sanity checks
732 // that we don't want to run
733 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
734 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
735 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
736 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
737 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700738
Ian Rogers62d6c772013-02-27 08:32:07 -0800739 if (verify_object_mode_ != kVerifyAllFast) {
740 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
741 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700742 if (!IsLiveObjectLocked(obj)) {
743 DumpSpaces();
744 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700745 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700746 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700747 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
748 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700749 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700750}
751
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800752void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700753 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700754 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700755}
756
757void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700758 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700759 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700760}
761
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700762inline size_t Heap::RecordAllocationInstrumented(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700763 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700764 DCHECK_GT(size, 0u);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700765 size_t old_num_bytes_allocated = static_cast<size_t>(num_bytes_allocated_.fetch_add(size));
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700766
767 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700768 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700769 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700770 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700771
772 // TODO: Update these atomically.
773 RuntimeStats* global_stats = Runtime::Current()->GetStats();
774 ++global_stats->allocated_objects;
775 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700776 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700777
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700778 // This is safe to do since the GC will never free objects which are neither in the allocation
779 // stack or the live bitmap.
780 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700781 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700782 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700783
784 return old_num_bytes_allocated + size;
Carl Shapiro58551df2011-07-24 03:09:51 -0700785}
786
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700787void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700788 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700789 num_bytes_allocated_.fetch_sub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700790
791 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700792 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700793 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700794 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700795
796 // TODO: Do this concurrently.
797 RuntimeStats* global_stats = Runtime::Current()->GetStats();
798 global_stats->freed_objects += freed_objects;
799 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700800 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700801}
802
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700803inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::AllocSpace* space, size_t alloc_size,
804 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700805 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700806 return NULL;
807 }
808 return space->Alloc(self, alloc_size, bytes_allocated);
809}
810
811// DlMallocSpace-specific version.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700812inline mirror::Object* Heap::TryToAllocateInstrumented(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
813 bool grow, size_t* bytes_allocated) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700814 if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700815 return NULL;
816 }
Mathieu Chartier720ef762013-08-17 14:46:54 -0700817 if (LIKELY(!running_on_valgrind_)) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700818 return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
819 } else {
820 return space->Alloc(self, alloc_size, bytes_allocated);
821 }
822}
823
824template <class T>
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700825inline mirror::Object* Heap::AllocateInstrumented(Thread* self, T* space, size_t alloc_size,
826 size_t* bytes_allocated) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700827 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
828 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700829 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700830 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700831
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700832 mirror::Object* ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
833 if (LIKELY(ptr != NULL)) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700834 return ptr;
835 }
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700836 return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
837}
838
Mathieu Chartier720ef762013-08-17 14:46:54 -0700839mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space,
840 size_t alloc_size, size_t* bytes_allocated) {
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700841 mirror::Object* ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700842
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700843 // The allocation failed. If the GC is running, block until it completes, and then retry the
844 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700845 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
846 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700847 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700848 ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700849 if (ptr != NULL) {
850 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700851 }
852 }
853
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700854 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700855 for (size_t i = static_cast<size_t>(last_gc) + 1;
856 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700857 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700858 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700859 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700860 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700861 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700862 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
863 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700864 break;
865 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700866 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700867 run_gc = have_zygote_space_;
868 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700869 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700870 run_gc = true;
871 break;
872 default:
873 break;
874 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700875
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700876 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700877 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700878 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800879 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700880 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700881
882 // Did we free sufficient memory for the allocation to succeed?
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700883 ptr = TryToAllocateInstrumented(self, space, alloc_size, false, bytes_allocated);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700884 if (ptr != NULL) {
885 return ptr;
886 }
887 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700888 }
889
890 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700891 // Try harder, growing the heap if necessary.
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700892 ptr = TryToAllocateInstrumented(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700893 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700894 return ptr;
895 }
896
Elliott Hughes81ff3182012-03-23 20:35:56 -0700897 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
898 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
899 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700900
Elliott Hughes418dfe72011-10-06 18:56:27 -0700901 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700902 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
903 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700904
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700905 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700906 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700907 return TryToAllocateInstrumented(self, space, alloc_size, true, bytes_allocated);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700908}
909
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700910void Heap::SetTargetHeapUtilization(float target) {
911 DCHECK_GT(target, 0.0f); // asserted in Java code
912 DCHECK_LT(target, 1.0f);
913 target_utilization_ = target;
914}
915
Ian Rogers1d54e732013-05-02 21:10:01 -0700916size_t Heap::GetObjectsAllocated() const {
917 size_t total = 0;
918 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
919 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
920 space::ContinuousSpace* space = *it;
921 if (space->IsDlMallocSpace()) {
922 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700923 }
924 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700925 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
926 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
927 space::DiscontinuousSpace* space = *it;
928 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
929 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700930 return total;
931}
932
Ian Rogers1d54e732013-05-02 21:10:01 -0700933size_t Heap::GetObjectsAllocatedEver() const {
934 size_t total = 0;
935 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
936 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
937 space::ContinuousSpace* space = *it;
938 if (space->IsDlMallocSpace()) {
939 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700940 }
941 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700942 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
943 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
944 space::DiscontinuousSpace* space = *it;
945 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
946 }
947 return total;
948}
949
950size_t Heap::GetBytesAllocatedEver() const {
951 size_t total = 0;
952 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
953 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
954 space::ContinuousSpace* space = *it;
955 if (space->IsDlMallocSpace()) {
956 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
957 }
958 }
959 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
960 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
961 space::DiscontinuousSpace* space = *it;
962 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
963 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700964 return total;
965}
966
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700967class InstanceCounter {
968 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800969 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700970 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800971 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700972 }
973
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800974 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800975 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800976 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800977 if (use_is_assignable_from_) {
978 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
979 ++counts_[i];
980 }
981 } else {
982 if (instance_class == classes_[i]) {
983 ++counts_[i];
984 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700985 }
986 }
987 }
988
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700989 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800990 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800991 bool use_is_assignable_from_;
992 uint64_t* const counts_;
993
994 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700995};
996
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800997void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800998 uint64_t* counts) {
999 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1000 // is empty, so the live bitmap is the only place we need to look.
1001 Thread* self = Thread::Current();
1002 self->TransitionFromRunnableToSuspended(kNative);
1003 CollectGarbage(false);
1004 self->TransitionFromSuspendedToRunnable();
1005
1006 InstanceCounter counter(classes, use_is_assignable_from, counts);
1007 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001008 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001009}
1010
Elliott Hughes3b78c942013-01-15 17:35:41 -08001011class InstanceCollector {
1012 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001013 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001014 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1015 : class_(c), max_count_(max_count), instances_(instances) {
1016 }
1017
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001018 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1019 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -08001020 if (instance_class == class_) {
1021 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001022 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -08001023 }
1024 }
1025 }
1026
1027 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001028 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001029 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001030 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001031
1032 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1033};
1034
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001035void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1036 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001037 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1038 // is empty, so the live bitmap is the only place we need to look.
1039 Thread* self = Thread::Current();
1040 self->TransitionFromRunnableToSuspended(kNative);
1041 CollectGarbage(false);
1042 self->TransitionFromSuspendedToRunnable();
1043
1044 InstanceCollector collector(c, max_count, instances);
1045 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1046 GetLiveBitmap()->Visit(collector);
1047}
1048
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001049class ReferringObjectsFinder {
1050 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001051 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1052 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001053 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1054 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1055 }
1056
1057 // For bitmap Visit.
1058 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1059 // annotalysis on visitors.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001060 void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1061 collector::MarkSweep::VisitObjectReferences(obj, *this, true);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001062 }
1063
1064 // For MarkSweep::VisitObjectReferences.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001065 void operator()(mirror::Object* referrer, mirror::Object* object,
Brian Carlstromdf629502013-07-17 22:39:56 -07001066 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001067 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001068 referring_objects_.push_back(referrer);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001069 }
1070 }
1071
1072 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001073 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001074 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001075 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001076
1077 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1078};
1079
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001080void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1081 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001082 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1083 // is empty, so the live bitmap is the only place we need to look.
1084 Thread* self = Thread::Current();
1085 self->TransitionFromRunnableToSuspended(kNative);
1086 CollectGarbage(false);
1087 self->TransitionFromSuspendedToRunnable();
1088
1089 ReferringObjectsFinder finder(o, max_count, referring_objects);
1090 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1091 GetLiveBitmap()->Visit(finder);
1092}
1093
Ian Rogers30fab402012-01-23 15:43:46 -08001094void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001095 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1096 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001097 Thread* self = Thread::Current();
1098 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001099 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001100}
1101
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001102void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001103 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001104 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1105 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001106 Thread* self = Thread::Current();
1107 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001108
1109 // Try to see if we have any Zygote spaces.
1110 if (have_zygote_space_) {
1111 return;
1112 }
1113
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001114 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1115
1116 {
1117 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001118 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001119 FlushAllocStack();
1120 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001121
Ian Rogers1d54e732013-05-02 21:10:01 -07001122 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1123 // of the remaining available heap memory.
1124 space::DlMallocSpace* zygote_space = alloc_space_;
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07001125 alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
Ian Rogers1d54e732013-05-02 21:10:01 -07001126 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001127
Ian Rogers1d54e732013-05-02 21:10:01 -07001128 // Change the GC retention policy of the zygote space to only collect when full.
1129 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1130 AddContinuousSpace(alloc_space_);
1131 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001132
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001133 // Create the zygote space mod union table.
1134 accounting::ModUnionTable* mod_union_table =
1135 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1136 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1137 AddModUnionTable(mod_union_table);
1138
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001139 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001140 for (const auto& collector : mark_sweep_collectors_) {
1141 collector->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001142 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001143}
1144
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001145void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001146 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1147 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001148 allocation_stack_->Reset();
1149}
1150
Ian Rogers1d54e732013-05-02 21:10:01 -07001151void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1152 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001153 mirror::Object** limit = stack->End();
1154 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1155 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001156 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001157 if (LIKELY(bitmap->HasAddress(obj))) {
1158 bitmap->Set(obj);
1159 } else {
1160 large_objects->Set(obj);
1161 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001162 }
1163}
1164
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001165
1166const char* gc_cause_and_type_strings[3][4] = {
1167 {"", "GC Alloc Sticky", "GC Alloc Partial", "GC Alloc Full"},
1168 {"", "GC Background Sticky", "GC Background Partial", "GC Background Full"},
1169 {"", "GC Explicit Sticky", "GC Explicit Partial", "GC Explicit Full"}};
1170
Ian Rogers1d54e732013-05-02 21:10:01 -07001171collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1172 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001173 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001174
Mathieu Chartier65db8802012-11-20 12:36:46 -08001175 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001176 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001177
Ian Rogers120f1c72012-09-28 17:17:10 -07001178 if (self->IsHandlingStackOverflow()) {
1179 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1180 }
1181
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001182 // Ensure there is only one GC at a time.
1183 bool start_collect = false;
1184 while (!start_collect) {
1185 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001186 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001187 if (!is_gc_running_) {
1188 is_gc_running_ = true;
1189 start_collect = true;
1190 }
1191 }
1192 if (!start_collect) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001193 // TODO: timinglog this.
Ian Rogers81d425b2012-09-27 16:03:43 -07001194 WaitForConcurrentGcToComplete(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001195
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001196 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1197 // Not doing at the moment to ensure soft references are cleared.
1198 }
1199 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001200 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001201
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001202 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1203 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1204 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1205 }
1206
Ian Rogers1d54e732013-05-02 21:10:01 -07001207 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001208 uint64_t gc_start_size = GetBytesAllocated();
1209 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001210 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001211 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1212 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001213 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001214 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001215 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001216 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1217 }
1218
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001219 if (gc_type == collector::kGcTypeSticky &&
1220 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1221 gc_type = collector::kGcTypePartial;
1222 }
1223
Ian Rogers1d54e732013-05-02 21:10:01 -07001224 DCHECK_LT(gc_type, collector::kGcTypeMax);
1225 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001226 DCHECK_LE(gc_cause, kGcCauseExplicit);
1227
1228 ATRACE_BEGIN(gc_cause_and_type_strings[gc_cause][gc_type]);
1229
Ian Rogers1d54e732013-05-02 21:10:01 -07001230 collector::MarkSweep* collector = NULL;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001231 for (const auto& cur_collector : mark_sweep_collectors_) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001232 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1233 collector = cur_collector;
1234 break;
1235 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001236 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001237 CHECK(collector != NULL)
1238 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1239 << " and type=" << gc_type;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001240
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001241 collector->clear_soft_references_ = clear_soft_references;
1242 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001243 total_objects_freed_ever_ += collector->GetFreedObjects();
1244 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001245 if (care_about_pause_times_) {
1246 const size_t duration = collector->GetDurationNs();
1247 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1248 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001249 bool was_slow = duration > long_gc_log_threshold_ ||
1250 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001251 if (!was_slow) {
1252 for (uint64_t pause : pauses) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001253 was_slow = was_slow || pause > long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001254 }
1255 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001256
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001257 if (was_slow) {
1258 const size_t percent_free = GetPercentFree();
1259 const size_t current_heap_size = GetBytesAllocated();
1260 const size_t total_memory = GetTotalMemory();
1261 std::ostringstream pause_string;
1262 for (size_t i = 0; i < pauses.size(); ++i) {
1263 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1264 << ((i != pauses.size() - 1) ? ", " : "");
1265 }
1266 LOG(INFO) << gc_cause << " " << collector->GetName()
1267 << " GC freed " << collector->GetFreedObjects() << "("
1268 << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1269 << collector->GetFreedLargeObjects() << "("
1270 << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1271 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1272 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1273 << " total " << PrettyDuration((duration / 1000) * 1000);
1274 if (VLOG_IS_ON(heap)) {
1275 LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
1276 }
1277 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001278 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001279
Ian Rogers15bf2d32012-08-28 17:33:04 -07001280 {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001281 MutexLock mu(self, *gc_complete_lock_);
1282 is_gc_running_ = false;
1283 last_gc_type_ = gc_type;
1284 // Wake anyone who may have been waiting for the GC to complete.
1285 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001286 }
Mathieu Chartier0a9dc052013-07-25 11:01:28 -07001287
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001288 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001289
1290 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001291 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001292 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001293}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001294
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001295static mirror::Object* RootMatchesObjectVisitor(mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001296 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001297 if (root == obj) {
1298 LOG(INFO) << "Object " << obj << " is a root";
1299 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001300 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001301}
1302
1303class ScanVisitor {
1304 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001305 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001306 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001307 }
1308};
1309
Ian Rogers1d54e732013-05-02 21:10:01 -07001310// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001311class VerifyReferenceVisitor {
1312 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001313 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001314 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001315 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001316
1317 bool Failed() const {
1318 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001319 }
1320
1321 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001322 // analysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001323 void operator()(const mirror::Object* obj, const mirror::Object* ref,
1324 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001325 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001326 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001327 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1328 accounting::CardTable* card_table = heap_->GetCardTable();
1329 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1330 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001331
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001332 if (!failed_) {
1333 // Print message on only on first failure to prevent spam.
1334 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
1335 failed_ = true;
1336 }
1337 if (obj != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001338 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001339 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
1340 << offset << "\n card value = " << static_cast<int>(*card_addr);
1341 if (heap_->IsHeapAddress(obj->GetClass())) {
1342 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1343 } else {
1344 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
1345 }
1346
1347 // Attmept to find the class inside of the recently freed objects.
1348 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
1349 if (ref_space->IsDlMallocSpace()) {
1350 space::DlMallocSpace* space = ref_space->AsDlMallocSpace();
1351 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
1352 if (ref_class != nullptr) {
1353 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
1354 << PrettyClass(ref_class);
1355 } else {
1356 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
1357 }
1358 }
1359
1360 if (ref->GetClass() != nullptr && heap_->IsHeapAddress(ref->GetClass()) &&
1361 ref->GetClass()->IsClass()) {
1362 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1363 } else {
1364 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
1365 << ") is not a valid heap address";
1366 }
1367
Ian Rogers1d54e732013-05-02 21:10:01 -07001368 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1369 void* cover_begin = card_table->AddrFromCard(card_addr);
1370 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1371 accounting::CardTable::kCardSize);
1372 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1373 << "-" << cover_end;
1374 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001375
Ian Rogers1d54e732013-05-02 21:10:01 -07001376 // Print out how the object is live.
1377 if (bitmap != NULL && bitmap->Test(obj)) {
1378 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1379 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001380 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001381 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1382 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001383 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001384 LOG(ERROR) << "Object " << obj << " found in live stack";
1385 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001386 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1387 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
1388 }
1389 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1390 LOG(ERROR) << "Ref " << ref << " found in live stack";
1391 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001392 // Attempt to see if the card table missed the reference.
1393 ScanVisitor scan_visitor;
1394 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1395 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001396 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Ian Rogers1d54e732013-05-02 21:10:01 -07001397
1398 // Search to see if any of the roots reference our object.
1399 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1400 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1401
1402 // Search to see if any of the roots reference our reference.
1403 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1404 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1405 } else {
1406 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001407 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001408 }
1409 }
1410
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001411 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001412 return heap_->IsLiveObjectLocked(obj, true, false, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001413 }
1414
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001415 static mirror::Object* VerifyRoots(mirror::Object* root, void* arg) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001416 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001417 (*visitor)(nullptr, root, MemberOffset(0), true);
1418 return root;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001419 }
1420
1421 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001422 Heap* const heap_;
1423 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001424};
1425
Ian Rogers1d54e732013-05-02 21:10:01 -07001426// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001427class VerifyObjectVisitor {
1428 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001429 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001430
Brian Carlstromdf629502013-07-17 22:39:56 -07001431 void operator()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001432 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001433 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1434 // be live or else how did we find it in the live bitmap?
1435 VerifyReferenceVisitor visitor(heap_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001436 // The class doesn't count as a reference but we should verify it anyways.
1437 visitor(obj, obj->GetClass(), MemberOffset(0), false);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001438 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(obj), visitor, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001439 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001440 }
1441
1442 bool Failed() const {
1443 return failed_;
1444 }
1445
1446 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001447 Heap* const heap_;
1448 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001449};
1450
1451// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001452bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001453 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001454 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001455 allocation_stack_->Sort();
1456 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001457 // Perform the verification.
1458 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001459 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001460 GetLiveBitmap()->Visit(visitor);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001461 // Verify objects in the allocation stack since these will be objects which were:
1462 // 1. Allocated prior to the GC (pre GC verification).
1463 // 2. Allocated during the GC (pre sweep GC verification).
1464 for (mirror::Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
1465 visitor(*it);
1466 }
1467 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001468 // pointing to dead objects if they are not reachable.
1469 if (visitor.Failed()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001470 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001471 for (const auto& table_pair : mod_union_tables_) {
1472 accounting::ModUnionTable* mod_union_table = table_pair.second;
1473 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
1474 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001475 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001476 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001477 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001478 return true;
1479}
1480
1481class VerifyReferenceCardVisitor {
1482 public:
1483 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1484 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1485 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001486 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001487 }
1488
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001489 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1490 // annotalysis on visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001491 void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1492 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001493 // Filter out class references since changing an object's class does not mark the card as dirty.
1494 // Also handles large objects, since the only reference they hold is a class reference.
1495 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001496 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001497 // If the object is not dirty and it is referencing something in the live stack other than
1498 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001499 if (!card_table->AddrIsInCardTable(obj)) {
1500 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1501 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001502 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001503 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1504 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001505 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001506 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
1507 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001508 LOG(ERROR) << "Object " << obj << " found in live stack";
1509 }
1510 if (heap_->GetLiveBitmap()->Test(obj)) {
1511 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1512 }
1513 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1514 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1515
1516 // Print which field of the object is dead.
1517 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001518 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001519 CHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001520 const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
1521 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001522 CHECK(fields != NULL);
1523 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001524 const mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001525 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1526 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1527 << PrettyField(cur);
1528 break;
1529 }
1530 }
1531 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001532 const mirror::ObjectArray<mirror::Object>* object_array =
1533 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001534 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1535 if (object_array->Get(i) == ref) {
1536 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1537 }
1538 }
1539 }
1540
1541 *failed_ = true;
1542 }
1543 }
1544 }
1545 }
1546
1547 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001548 Heap* const heap_;
1549 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001550};
1551
1552class VerifyLiveStackReferences {
1553 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001554 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001555 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001556 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001557
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001558 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001559 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1560 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001561 collector::MarkSweep::VisitObjectReferences(obj, visitor, true);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001562 }
1563
1564 bool Failed() const {
1565 return failed_;
1566 }
1567
1568 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001569 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001570 bool failed_;
1571};
1572
1573bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001574 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001575
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001576 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001577 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001578 VerifyLiveStackReferences visitor(this);
1579 GetLiveBitmap()->Visit(visitor);
1580
1581 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001582 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001583 visitor(*it);
1584 }
1585
1586 if (visitor.Failed()) {
1587 DumpSpaces();
1588 return false;
1589 }
1590 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001591}
1592
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001593void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001594 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001595}
1596
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001597accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
1598 auto it = mod_union_tables_.find(space);
1599 if (it == mod_union_tables_.end()) {
1600 return nullptr;
1601 }
1602 return it->second;
1603}
1604
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001605void Heap::ProcessCards(base::TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001606 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001607 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001608 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
1609 if (table != nullptr) {
1610 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
1611 "ImageModUnionClearCards";
1612 base::TimingLogger::ScopedSplit split(name, &timings);
1613 table->ClearCards();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001614 } else {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001615 base::TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001616 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1617 // were dirty before the GC started.
1618 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001619 }
1620 }
1621}
1622
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001623static mirror::Object* IdentityCallback(mirror::Object* obj, void*) {
1624 return obj;
1625}
1626
Ian Rogers1d54e732013-05-02 21:10:01 -07001627void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001628 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1629 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001630
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001631 if (verify_pre_gc_heap_) {
1632 thread_list->SuspendAll();
1633 {
1634 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1635 if (!VerifyHeapReferences()) {
1636 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1637 }
1638 }
1639 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001640 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001641
1642 // Check that all objects which reference things in the live stack are on dirty cards.
1643 if (verify_missing_card_marks_) {
1644 thread_list->SuspendAll();
1645 {
1646 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1647 SwapStacks();
1648 // Sort the live stack so that we can quickly binary search it later.
1649 if (!VerifyMissingCardMarks()) {
1650 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1651 }
1652 SwapStacks();
1653 }
1654 thread_list->ResumeAll();
1655 }
1656
1657 if (verify_mod_union_table_) {
1658 thread_list->SuspendAll();
1659 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001660 for (const auto& table_pair : mod_union_tables_) {
1661 accounting::ModUnionTable* mod_union_table = table_pair.second;
1662 mod_union_table->UpdateAndMarkReferences(IdentityCallback, nullptr);
1663 mod_union_table->Verify();
1664 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001665 thread_list->ResumeAll();
1666 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001667}
1668
Ian Rogers1d54e732013-05-02 21:10:01 -07001669void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001670 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1671 // reachable objects.
1672 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001673 Thread* self = Thread::Current();
1674 CHECK_NE(self->GetState(), kRunnable);
Ian Rogers1d54e732013-05-02 21:10:01 -07001675 {
1676 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1677 // Swapping bound bitmaps does nothing.
1678 gc->SwapBitmaps();
1679 if (!VerifyHeapReferences()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001680 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
Ian Rogers1d54e732013-05-02 21:10:01 -07001681 }
1682 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001683 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001684 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001685}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001686
Ian Rogers1d54e732013-05-02 21:10:01 -07001687void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001688 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001689 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001690 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001691 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001692 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001693 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001694}
1695
Ian Rogers1d54e732013-05-02 21:10:01 -07001696collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1697 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001698 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001699 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001700 bool do_wait;
1701 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001702 {
1703 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001704 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001705 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001706 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001707 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001708 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001709 // We must wait, change thread state then sleep on gc_complete_cond_;
1710 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1711 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001712 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001713 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001714 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001715 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001716 last_gc_type = last_gc_type_;
Brian Carlstromf69863b2013-07-17 21:53:13 -07001717 wait_time = NanoTime() - wait_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001718 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001719 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001720 if (wait_time > long_pause_log_threshold_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001721 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1722 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001723 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001724 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001725 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001726 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001727}
1728
Elliott Hughesc967f782012-04-16 10:23:15 -07001729void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001730 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001731 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001732 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001733}
1734
1735size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001736 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001737}
1738
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001739void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001740 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001741 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001742 << PrettySize(GetMaxMemory());
1743 max_allowed_footprint = GetMaxMemory();
1744 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001745 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001746}
1747
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001748void Heap::UpdateMaxNativeFootprint() {
1749 size_t native_size = native_bytes_allocated_;
1750 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1751 size_t target_size = native_size / GetTargetHeapUtilization();
1752 if (target_size > native_size + max_free_) {
1753 target_size = native_size + max_free_;
1754 } else if (target_size < native_size + min_free_) {
1755 target_size = native_size + min_free_;
1756 }
1757 native_footprint_gc_watermark_ = target_size;
1758 native_footprint_limit_ = 2 * target_size - native_size;
1759}
1760
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001761void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001762 // We know what our utilization is at this moment.
1763 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001764 const size_t bytes_allocated = GetBytesAllocated();
1765 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001766 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001767
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001768 size_t target_size;
1769 if (gc_type != collector::kGcTypeSticky) {
1770 // Grow the heap for non sticky GC.
1771 target_size = bytes_allocated / GetTargetHeapUtilization();
1772 if (target_size > bytes_allocated + max_free_) {
1773 target_size = bytes_allocated + max_free_;
1774 } else if (target_size < bytes_allocated + min_free_) {
1775 target_size = bytes_allocated + min_free_;
1776 }
1777 next_gc_type_ = collector::kGcTypeSticky;
1778 } else {
1779 // Based on how close the current heap size is to the target size, decide
1780 // whether or not to do a partial or sticky GC next.
1781 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1782 next_gc_type_ = collector::kGcTypeSticky;
1783 } else {
1784 next_gc_type_ = collector::kGcTypePartial;
1785 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001786
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001787 // If we have freed enough memory, shrink the heap back down.
1788 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1789 target_size = bytes_allocated + max_free_;
1790 } else {
1791 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1792 }
1793 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001794
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001795 if (!ignore_max_footprint_) {
1796 SetIdealFootprint(target_size);
1797
1798 if (concurrent_gc_) {
1799 // Calculate when to perform the next ConcurrentGC.
1800
1801 // Calculate the estimated GC duration.
1802 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1803 // Estimate how many remaining bytes we will have when we need to start the next GC.
1804 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
1805 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1806 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1807 // A never going to happen situation that from the estimated allocation rate we will exceed
1808 // the applications entire footprint with the given estimated allocation rate. Schedule
1809 // another GC straight away.
1810 concurrent_start_bytes_ = bytes_allocated;
1811 } else {
1812 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1813 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1814 // right away.
1815 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
1816 }
1817 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1818 DCHECK_LE(max_allowed_footprint_, growth_limit_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001819 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001820 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001821
1822 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001823}
1824
jeffhaoc1160702011-10-27 15:48:45 -07001825void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001826 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001827 alloc_space_->ClearGrowthLimit();
1828}
1829
Elliott Hughesadb460d2011-10-05 17:02:34 -07001830void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001831 MemberOffset reference_queue_offset,
1832 MemberOffset reference_queueNext_offset,
1833 MemberOffset reference_pendingNext_offset,
1834 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001835 reference_referent_offset_ = reference_referent_offset;
1836 reference_queue_offset_ = reference_queue_offset;
1837 reference_queueNext_offset_ = reference_queueNext_offset;
1838 reference_pendingNext_offset_ = reference_pendingNext_offset;
1839 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1840 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1841 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1842 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1843 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1844 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1845}
1846
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001847mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001848 DCHECK(reference != NULL);
1849 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001850 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001851}
1852
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001853void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001854 DCHECK(reference != NULL);
1855 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1856 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1857}
1858
1859// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001860bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001861 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001862 const mirror::Object* queue =
1863 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1864 const mirror::Object* queue_next =
1865 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001866 return (queue != NULL) && (queue_next == NULL);
1867}
1868
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001869void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001870 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001871 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1872 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001873 EnqueuePendingReference(ref, cleared_reference_list);
1874}
1875
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001876bool Heap::IsEnqueued(mirror::Object* ref) {
1877 // Since the references are stored as cyclic lists it means that once enqueued, the pending next
1878 // will always be non-null.
1879 return ref->GetFieldObject<mirror::Object*>(GetReferencePendingNextOffset(), false) != nullptr;
1880}
1881
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001882void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001883 DCHECK(ref != NULL);
1884 DCHECK(list != NULL);
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001885 if (*list == NULL) {
1886 // 1 element cyclic queue, ie: Reference ref = ..; ref.pendingNext = ref;
1887 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1888 *list = ref;
1889 } else {
1890 mirror::Object* head =
1891 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
1892 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1893 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001894 }
1895}
1896
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001897mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001898 DCHECK(list != NULL);
1899 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001900 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1901 false);
1902 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001903
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001904 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1905 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001906 if (*list == head) {
1907 ref = *list;
1908 *list = NULL;
1909 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001910 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1911 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001912 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1913 ref = head;
1914 }
1915 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1916 return ref;
1917}
1918
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001919void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001920 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001921 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001922 ArgArray arg_array(NULL, 0);
1923 arg_array.Append(reinterpret_cast<uint32_t>(object));
1924 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001925 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001926}
1927
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001928void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001929 DCHECK(cleared != NULL);
1930 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001931 // When a runtime isn't started there are no reference queues to care about so ignore.
1932 if (LIKELY(Runtime::Current()->IsStarted())) {
1933 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001934 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001935 ArgArray arg_array(NULL, 0);
1936 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1937 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001938 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001939 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001940 *cleared = NULL;
1941 }
1942}
1943
Ian Rogers1f539342012-10-03 21:09:42 -07001944void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001945 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001946 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001947 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001948 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001949 !runtime->IsConcurrentGcEnabled()) {
1950 return;
1951 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001952 {
1953 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1954 if (runtime->IsShuttingDown()) {
1955 return;
1956 }
1957 }
1958 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001959 return;
1960 }
1961
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001962 // We already have a request pending, no reason to start more until we update
1963 // concurrent_start_bytes_.
1964 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1965
Ian Rogers120f1c72012-09-28 17:17:10 -07001966 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001967 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1968 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001969 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1970 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001971 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001972}
1973
Ian Rogers81d425b2012-09-27 16:03:43 -07001974void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001975 {
1976 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001977 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001978 return;
1979 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001980 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001981
Mathieu Chartier65db8802012-11-20 12:36:46 -08001982 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001983 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001984 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001985 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001986}
1987
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001988void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001989 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1990 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1991 // a space it will hold its lock and can become a cause of jank.
1992 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1993 // forking.
1994
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001995 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1996 // because that only marks object heads, so a large array looks like lots of empty space. We
1997 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1998 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1999 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2000 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08002001 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002002 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07002003 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
Mathieu Chartiere0a53e92013-08-05 10:17:40 -07002004 if ((utilization > 0.75f && !IsLowMemoryMode()) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
2005 // Don't bother trimming the alloc space if it's more than 75% utilized and low memory mode is
2006 // not enabled, or if a heap trim occurred in the last two seconds.
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002007 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002008 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002009
2010 Thread* self = Thread::Current();
2011 {
2012 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2013 Runtime* runtime = Runtime::Current();
2014 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
2015 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2016 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2017 // as we don't hold the lock while requesting the trim).
2018 return;
2019 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08002020 }
Ian Rogers48931882013-01-22 14:35:16 -08002021
Ian Rogers1d54e732013-05-02 21:10:01 -07002022 last_trim_time_ms_ = ms_time;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002023 ListenForProcessStateChange();
2024
2025 // Trim only if we do not currently care about pause times.
2026 if (!care_about_pause_times_) {
2027 JNIEnv* env = self->GetJniEnv();
2028 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
2029 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
2030 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2031 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2032 CHECK(!env->ExceptionCheck());
2033 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002034}
2035
Ian Rogers48931882013-01-22 14:35:16 -08002036size_t Heap::Trim() {
2037 // Handle a requested heap trim on a thread outside of the main GC thread.
2038 return alloc_space_->Trim();
2039}
2040
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002041bool Heap::IsGCRequestPending() const {
2042 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2043}
2044
2045void Heap::RegisterNativeAllocation(int bytes) {
2046 // Total number of native bytes allocated.
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002047 native_bytes_allocated_.fetch_add(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002048 Thread* self = Thread::Current();
2049 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_) {
2053 JNIEnv* env = self->GetJniEnv();
2054 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
2055 // point.
2056 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
2057 DCHECK(WellKnownClasses::java_lang_System != NULL);
2058 WellKnownClasses::java_lang_System_runFinalization =
2059 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2060 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
2061 }
2062 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
2063 // Just finished a GC, attempt to run finalizers.
2064 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2065 WellKnownClasses::java_lang_System_runFinalization);
2066 CHECK(!env->ExceptionCheck());
2067 }
2068
2069 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2070 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2071 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
2072 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2073 WellKnownClasses::java_lang_System_runFinalization);
2074 CHECK(!env->ExceptionCheck());
2075 }
2076 // We have just run finalizers, update the native watermark since it is very likely that
2077 // finalizers released native managed allocations.
2078 UpdateMaxNativeFootprint();
2079 } else {
2080 if (!IsGCRequestPending()) {
2081 RequestConcurrentGC(self);
2082 }
2083 }
2084 }
2085}
2086
2087void Heap::RegisterNativeFree(int bytes) {
2088 int expected_size, new_size;
2089 do {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002090 expected_size = native_bytes_allocated_.load();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002091 new_size = expected_size - bytes;
2092 if (new_size < 0) {
2093 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
2094 bytes, expected_size);
2095 break;
2096 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07002097 } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002098}
2099
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002100int64_t Heap::GetTotalMemory() const {
2101 int64_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002102 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002103 if (space->IsImageSpace()) {
2104 // Currently don't include the image space.
2105 } else if (space->IsDlMallocSpace()) {
2106 // Zygote or alloc space
2107 ret += space->AsDlMallocSpace()->GetFootprint();
2108 }
2109 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002110 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002111 if (space->IsLargeObjectSpace()) {
2112 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2113 }
2114 }
2115 return ret;
2116}
2117
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002118void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
2119 DCHECK(mod_union_table != nullptr);
2120 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
2121}
2122
Ian Rogers1d54e732013-05-02 21:10:01 -07002123} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002124} // namespace art