blob: eae152083e1df994e7643d4cb823aec8e6351a3b [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#include <sys/types.h>
22#include <sys/wait.h>
23
Brian Carlstrom58ae9412011-10-04 00:56:06 -070024#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070025#include <vector>
26
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070028#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080029#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070030#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070031#include "gc/accounting/atomic_stack.h"
32#include "gc/accounting/card_table-inl.h"
33#include "gc/accounting/heap_bitmap-inl.h"
34#include "gc/accounting/mod_union_table-inl.h"
35#include "gc/accounting/space_bitmap-inl.h"
36#include "gc/collector/mark_sweep-inl.h"
37#include "gc/collector/partial_mark_sweep.h"
38#include "gc/collector/sticky_mark_sweep.h"
39#include "gc/space/image_space.h"
40#include "gc/space/large_object_space.h"
41#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070042#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080043#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/class-inl.h"
45#include "mirror/field-inl.h"
46#include "mirror/object.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080049#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080050#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070051#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070052#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070053#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070054#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070055#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070056#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070057
58namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070059namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070060
Ian Rogers1d54e732013-05-02 21:10:01 -070061// When to create a log message about a slow GC, 100ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080062static const uint64_t kSlowGcThreshold = MsToNs(100);
Ian Rogers1d54e732013-05-02 21:10:01 -070063// When to create a log message about a slow pause, 5ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080064static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080065static const bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070066// Minimum amount of remaining bytes before a concurrent GC is triggered.
67static const size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070068const double Heap::kDefaultTargetUtilization = 0.5;
69
Elliott Hughesae80b492012-04-24 10:43:17 -070070static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080071 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080072 std::vector<std::string> boot_class_path;
73 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070074 if (boot_class_path.empty()) {
75 LOG(FATAL) << "Failed to generate image because no boot class path specified";
76 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080077
78 std::vector<char*> arg_vector;
79
80 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070081 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080082 const char* dex2oat = dex2oat_string.c_str();
83 arg_vector.push_back(strdup(dex2oat));
84
85 std::string image_option_string("--image=");
86 image_option_string += image_file_name;
87 const char* image_option = image_option_string.c_str();
88 arg_vector.push_back(strdup(image_option));
89
90 arg_vector.push_back(strdup("--runtime-arg"));
91 arg_vector.push_back(strdup("-Xms64m"));
92
93 arg_vector.push_back(strdup("--runtime-arg"));
94 arg_vector.push_back(strdup("-Xmx64m"));
95
96 for (size_t i = 0; i < boot_class_path.size(); i++) {
97 std::string dex_file_option_string("--dex-file=");
98 dex_file_option_string += boot_class_path[i];
99 const char* dex_file_option = dex_file_option_string.c_str();
100 arg_vector.push_back(strdup(dex_file_option));
101 }
102
103 std::string oat_file_option_string("--oat-file=");
104 oat_file_option_string += image_file_name;
105 oat_file_option_string.erase(oat_file_option_string.size() - 3);
106 oat_file_option_string += "oat";
107 const char* oat_file_option = oat_file_option_string.c_str();
108 arg_vector.push_back(strdup(oat_file_option));
109
jeffhao8161c032012-10-31 15:50:00 -0700110 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
111 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800112
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700113 if (kIsTargetBuild) {
114 arg_vector.push_back(strdup("--image-classes-zip=/system/framework/framework.jar"));
115 arg_vector.push_back(strdup("--image-classes=preloaded-classes"));
116 } else {
Brian Carlstrom265091e2013-01-30 14:08:26 -0800117 arg_vector.push_back(strdup("--host"));
118 }
119
Elliott Hughes48436bb2012-02-07 15:23:28 -0800120 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800121 LOG(INFO) << command_line;
122
Elliott Hughes48436bb2012-02-07 15:23:28 -0800123 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800124 char** argv = &arg_vector[0];
125
126 // fork and exec dex2oat
127 pid_t pid = fork();
128 if (pid == 0) {
129 // no allocation allowed between fork and exec
130
131 // change process groups, so we don't get reaped by ProcessManager
132 setpgid(0, 0);
133
134 execv(dex2oat, argv);
135
136 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
137 return false;
138 } else {
139 STLDeleteElements(&arg_vector);
140
141 // wait for dex2oat to finish
142 int status;
143 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
144 if (got_pid != pid) {
145 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
146 return false;
147 }
148 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
149 LOG(ERROR) << dex2oat << " failed: " << command_line;
150 return false;
151 }
152 }
153 return true;
154}
155
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700156void Heap::UnReserveOatFileAddressRange() {
157 oat_file_map_.reset(NULL);
158}
159
Mathieu Chartier0051be62012-10-12 17:47:11 -0700160Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
161 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700162 const std::string& original_image_file_name, bool concurrent_gc)
163 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800164 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700165 concurrent_gc_(concurrent_gc),
166 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -0700167 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800168 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -0700169 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700170 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800171 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700172 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700173 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700174 native_footprint_gc_watermark_(initial_size),
175 native_footprint_limit_(2 * initial_size),
Ian Rogers1d54e732013-05-02 21:10:01 -0700176 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
177 : std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700178 total_bytes_freed_ever_(0),
179 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700180 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800181 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700182 native_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700183 verify_missing_card_marks_(false),
184 verify_system_weaks_(false),
185 verify_pre_gc_heap_(false),
186 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700187 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700188 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700189 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700190 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800191 allocation_rate_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -0700192 max_allocation_stack_size_(kDesiredHeapVerification > kNoHeapVerification? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800193 reference_referent_offset_(0),
194 reference_queue_offset_(0),
195 reference_queueNext_offset_(0),
196 reference_pendingNext_offset_(0),
197 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700198 min_free_(min_free),
199 max_free_(max_free),
200 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700201 total_wait_time_(0),
202 measure_allocation_time_(false),
203 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700204 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800205 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800206 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700207 }
208
Ian Rogers1d54e732013-05-02 21:10:01 -0700209 live_bitmap_.reset(new accounting::HeapBitmap(this));
210 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700211
Ian Rogers30fab402012-01-23 15:43:46 -0800212 // Requested begin for the alloc space, to follow the mapped image and oat files
213 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800214 std::string image_file_name(original_image_file_name);
215 if (!image_file_name.empty()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700216 space::ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700217
Brian Carlstrom5643b782012-02-05 12:32:53 -0800218 if (OS::FileExists(image_file_name.c_str())) {
219 // If the /system file exists, it should be up-to-date, don't try to generate
Ian Rogers1d54e732013-05-02 21:10:01 -0700220 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800221 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -0700222 // If the /system file didn't exist, we need to use one from the dalvik-cache.
Brian Carlstrom5643b782012-02-05 12:32:53 -0800223 // If the cache file exists, try to open, but if it fails, regenerate.
224 // If it does not exist, generate.
Brian Carlstrom7675e162013-06-10 16:18:04 -0700225 image_file_name = GetDalvikCacheFilenameOrDie(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800226 if (OS::FileExists(image_file_name.c_str())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700227 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800228 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700229 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700230 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700231 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800232 }
233 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700234
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700235 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700236 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800237 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
238 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800239 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
240 CHECK_GT(oat_file_end_addr, image_space->End());
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700241
242 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
243 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800244 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr), kPageSize);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700245 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
246 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800247 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700248
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800249 if (oat_file_end_addr > requested_begin) {
250 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700251 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700252 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700253 }
254
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700255 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700256 const bool kUseFreeListSpaceForLOS = false;
257 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700258 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700259 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700260 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700261 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700262 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
263 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700264
Ian Rogers1d54e732013-05-02 21:10:01 -0700265 alloc_space_ = space::DlMallocSpace::Create("alloc space",
266 initial_size,
267 growth_limit, capacity,
268 requested_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700269 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700270 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700271 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700272
Ian Rogers1d54e732013-05-02 21:10:01 -0700273 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
274 byte* heap_begin = continuous_spaces_.front()->Begin();
275 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
276 if (continuous_spaces_.back()->IsDlMallocSpace()) {
277 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700278 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700279
Ian Rogers30fab402012-01-23 15:43:46 -0800280 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700281 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700282 typedef std::vector<space::ContinuousSpace*>::iterator It;
283 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
284 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800285 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700286 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700287 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800288 }
289 }
290
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800291 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700292 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700293 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700294
Ian Rogers1d54e732013-05-02 21:10:01 -0700295 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
296 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700297
Ian Rogers1d54e732013-05-02 21:10:01 -0700298 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700299 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700300
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700301 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700302 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800304 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700305 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700306 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
307 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
308 max_allocation_stack_size_));
309 live_stack_.reset(accounting::ObjectStack::Create("live stack",
310 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700311
Mathieu Chartier65db8802012-11-20 12:36:46 -0800312 // It's still too early to take a lock because there are no threads yet, but we can create locks
313 // now. We don't create it earlier to make it clear that you can't use locks during heap
314 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700315 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700316 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
317 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700318
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700319 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700320 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700321
Ian Rogers1d54e732013-05-02 21:10:01 -0700322 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800323 last_gc_size_ = GetBytesAllocated();
324
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800325 // Create our garbage collectors.
326 for (size_t i = 0; i < 2; ++i) {
327 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700328 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
329 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
330 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700331 }
332
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800333 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800334 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800335 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700336 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700337}
338
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700339void Heap::CreateThreadPool() {
340 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
341 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
342 // workers to complete.
Ian Rogers1d54e732013-05-02 21:10:01 -0700343 thread_pool_.reset(new ThreadPool(1)); // new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700344}
345
346void Heap::DeleteThreadPool() {
347 thread_pool_.reset(NULL);
348}
349
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700350// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700351struct ContinuousSpaceSorter {
352 bool operator ()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700353 return a->Begin() < b->Begin();
354 }
355};
356
Ian Rogers1d54e732013-05-02 21:10:01 -0700357void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700358 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700359 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700360 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700361 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700362 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700363 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
364 continuous_spaces_.push_back(space);
365 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
366 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700367 }
368
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700369 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700370 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700371
372 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
373 // avoid redundant marking.
374 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700375 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
376 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
377 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700378 if (space->IsImageSpace()) {
379 DCHECK(!seen_zygote);
380 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700381 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700382 DCHECK(!seen_alloc);
383 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700384 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700385 seen_alloc = true;
386 }
387 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800388}
389
Ian Rogers1d54e732013-05-02 21:10:01 -0700390void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
391 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
392 DCHECK(space != NULL);
393 DCHECK(space->GetLiveObjects() != NULL);
394 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
395 DCHECK(space->GetMarkObjects() != NULL);
396 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
397 discontinuous_spaces_.push_back(space);
398}
399
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700400void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700401 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700402 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700403 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800404
405 // Dump cumulative loggers for each GC type.
406 // TODO: C++0x
407 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700408 typedef std::vector<collector::MarkSweep*>::const_iterator It;
409 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800410 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700411 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800412 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800413 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700414 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800415 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700416 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800417 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
418 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
419 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700420 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
421 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
422 << collector->GetName() << " freed: " << freed_objects
423 << " objects with total size " << PrettySize(freed_bytes) << "\n"
424 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
425 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800426 total_duration += total_ns;
427 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700428 }
429 }
430 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700431 size_t total_objects_allocated = GetObjectsAllocatedEver();
432 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700433 if (total_duration != 0) {
434 const double total_seconds = double(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700435 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
436 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700437 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700438 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700439 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700440 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700441 os << "Total number of allocations: " << total_objects_allocated << "\n";
442 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700443 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700444 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
445 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
446 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700447 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700448 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
449 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700450}
451
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800452Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700453 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700454 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700455 }
456
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800457 STLDeleteElements(&mark_sweep_collectors_);
458
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700459 // If we don't reset then the mark stack complains in it's destructor.
460 allocation_stack_->Reset();
461 live_stack_->Reset();
462
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800463 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800464 // We can't take the heap lock here because there might be a daemon thread suspended with the
465 // heap lock held. We know though that no non-daemon threads are executing, and we know that
466 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
467 // those threads can't resume. We're the only running thread, and we can do whatever we like...
Ian Rogers1d54e732013-05-02 21:10:01 -0700468 STLDeleteElements(&continuous_spaces_);
469 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700471 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700472}
473
Ian Rogers1d54e732013-05-02 21:10:01 -0700474space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
475 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700476 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700477 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
478 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700479 if ((*it)->Contains(obj)) {
480 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700481 }
482 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700483 if (!fail_ok) {
484 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
485 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700486 return NULL;
487}
488
Ian Rogers1d54e732013-05-02 21:10:01 -0700489space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
490 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700491 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700492 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
493 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
494 if ((*it)->Contains(obj)) {
495 return *it;
496 }
497 }
498 if (!fail_ok) {
499 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
500 }
501 return NULL;
502}
503
504space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
505 space::Space* result = FindContinuousSpaceFromObject(obj, true);
506 if (result != NULL) {
507 return result;
508 }
509 return FindDiscontinuousSpaceFromObject(obj, true);
510}
511
512space::ImageSpace* Heap::GetImageSpace() const {
513 // TODO: C++0x auto
514 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
515 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700516 if ((*it)->IsImageSpace()) {
517 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700518 }
519 }
520 return NULL;
521}
522
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700523static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700524 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700525 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700526 size_t chunk_free_bytes = chunk_size - used_bytes;
527 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
528 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700529 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700530}
531
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800532mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
533 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700534 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
535 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800536 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700537
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800538 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700539 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700540 uint64_t allocation_start = 0;
541 if (measure_allocation_time_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700542 allocation_start = NanoTime() / kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700543 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700544
545 // We need to have a zygote space or else our newly allocated large object can end up in the
546 // Zygote resulting in it being prematurely freed.
547 // We can only do this for primive objects since large objects will not be within the card table
548 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers22a20862013-03-16 16:34:57 -0700549 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700550 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700551 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700552 // Make sure that our large object didn't get placed anywhere within the space interval or else
553 // it breaks the immune range.
554 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700555 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
556 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700557 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700558 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700559
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700560 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700561 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700562 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700563 }
564
Mathieu Chartier037813d2012-08-23 16:44:59 -0700565 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700566 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700567
568 // Record allocation after since we want to use the atomic add for the atomic fence to guard
569 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700570 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700571
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572 if (Dbg::IsAllocTrackingEnabled()) {
573 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700574 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700575 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700576 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800577 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700578 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700579 }
580 VerifyObject(obj);
581
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700582 if (measure_allocation_time_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700583 total_allocation_time_ += NanoTime() / kTimeAdjust - allocation_start;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700584 }
585
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700586 return obj;
587 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800588 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700589 int64_t total_bytes_free = GetFreeMemory();
Ian Rogers1d54e732013-05-02 21:10:01 -0700590 uint64_t alloc_space_size = alloc_space_->GetBytesAllocated();
591 uint64_t large_object_size = large_object_space_->GetObjectsAllocated();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800592 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
593 << " free bytes; allocation space size " << alloc_space_size
594 << "; large object space size " << large_object_size;
595 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
596 if (total_bytes_free >= byte_count) {
597 size_t max_contiguous_allocation = 0;
598 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700599 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
600 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
601 space::ContinuousSpace* space = *it;
602 if (space->IsDlMallocSpace()) {
603 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800604 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700605 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800606 oss << "; failed due to fragmentation (largest possible contiguous allocation "
607 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700608 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800609 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700610 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700611}
612
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800613bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700614 // Note: we deliberately don't take the lock here, and mustn't test anything that would
615 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700616 if (obj == NULL) {
617 return true;
618 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700619 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700620 return false;
621 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700622 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700623}
624
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800625bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700626 //Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
627 if (obj == NULL) {
628 return false;
629 }
630 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
631 return false;
632 }
633 space::ContinuousSpace* cont_space = FindContinuousSpaceFromObject(obj, true);
634 if (cont_space != NULL) {
635 if (cont_space->GetLiveBitmap()->Test(obj)) {
636 return true;
637 }
638 } else {
639 space::DiscontinuousSpace* disc_space = FindDiscontinuousSpaceFromObject(obj, true);
640 if (disc_space != NULL) {
641 if (disc_space->GetLiveObjects()->Test(obj)) {
642 return true;
643 }
644 }
645 }
646 for (size_t i = 0; i < 5; ++i) {
647 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
648 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
649 return true;
650 }
651 NanoSleep(MsToNs(10));
652 }
653 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700654}
655
Ian Rogers04d7aa92013-03-16 14:29:17 -0700656void Heap::VerifyObjectImpl(const mirror::Object* obj) {
657 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700658 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700659 return;
660 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700661 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700662}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700663
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700664void Heap::DumpSpaces() {
665 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700666 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
667 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
668 space::ContinuousSpace* space = *it;
669 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
670 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700671 LOG(INFO) << space << " " << *space << "\n"
672 << live_bitmap << " " << *live_bitmap << "\n"
673 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700674 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700675 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
676 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
677 space::DiscontinuousSpace* space = *it;
678 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700679 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700680}
681
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800682void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800683 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700684 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700685 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800686 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
687 return;
688 }
689 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
690 mirror::Object::ClassOffset().Int32Value();
691 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
692 if (UNLIKELY(c == NULL)) {
693 LOG(FATAL) << "Null class in object: " << obj;
694 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
695 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
696 }
697 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
698 // Note: we don't use the accessors here as they have internal sanity checks
699 // that we don't want to run
700 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
701 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
702 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
703 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
704 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700705
Ian Rogers62d6c772013-02-27 08:32:07 -0800706 if (verify_object_mode_ != kVerifyAllFast) {
707 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
708 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700709 if (!IsLiveObjectLocked(obj)) {
710 DumpSpaces();
711 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700712 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700713 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700714 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
715 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700716 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700717}
718
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800719void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700720 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700721 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700722}
723
724void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700725 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700726 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700727}
728
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800729void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700730 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700731 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700732 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700733
734 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700735 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700736 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700737 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700738
739 // TODO: Update these atomically.
740 RuntimeStats* global_stats = Runtime::Current()->GetStats();
741 ++global_stats->allocated_objects;
742 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700743 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700744
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700745 // This is safe to do since the GC will never free objects which are neither in the allocation
746 // stack or the live bitmap.
747 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700748 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700749 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700750}
751
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700752void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700753 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
754 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700755
756 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700757 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700758 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700759 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700760
761 // TODO: Do this concurrently.
762 RuntimeStats* global_stats = Runtime::Current()->GetStats();
763 global_stats->freed_objects += freed_objects;
764 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700765 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700766}
767
Ian Rogers1d54e732013-05-02 21:10:01 -0700768mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
769 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700770 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800771 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
772 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
773 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
774 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700775 return NULL;
776 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700777 }
778
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700779 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700780}
781
Ian Rogers1d54e732013-05-02 21:10:01 -0700782mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700783 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
784 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700785 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700786 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700787
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800788 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700789 if (ptr != NULL) {
790 return ptr;
791 }
792
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700793 // The allocation failed. If the GC is running, block until it completes, and then retry the
794 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700795 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
796 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700797 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700798 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700799 if (ptr != NULL) {
800 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700801 }
802 }
803
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700804 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700805 for (size_t i = static_cast<size_t>(last_gc) + 1;
806 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700807 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700808 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700809 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700810 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700811 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700812 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
813 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700814 break;
815 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700816 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700817 run_gc = have_zygote_space_;
818 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700819 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700820 run_gc = true;
821 break;
822 default:
823 break;
824 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700825
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700826 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700827 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700828 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800829 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700830 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700831
832 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700833 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700834 if (ptr != NULL) {
835 return ptr;
836 }
837 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700838 }
839
840 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700841 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700842 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700843 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700844 return ptr;
845 }
846
Elliott Hughes81ff3182012-03-23 20:35:56 -0700847 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
848 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
849 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700850
Elliott Hughes418dfe72011-10-06 18:56:27 -0700851 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700852 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
853 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700854
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700855 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700856 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700857 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700858}
859
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700860void Heap::SetTargetHeapUtilization(float target) {
861 DCHECK_GT(target, 0.0f); // asserted in Java code
862 DCHECK_LT(target, 1.0f);
863 target_utilization_ = target;
864}
865
Ian Rogers1d54e732013-05-02 21:10:01 -0700866size_t Heap::GetObjectsAllocated() const {
867 size_t total = 0;
868 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
869 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
870 space::ContinuousSpace* space = *it;
871 if (space->IsDlMallocSpace()) {
872 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700873 }
874 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700875 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
876 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
877 space::DiscontinuousSpace* space = *it;
878 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
879 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700880 return total;
881}
882
Ian Rogers1d54e732013-05-02 21:10:01 -0700883size_t Heap::GetObjectsAllocatedEver() const {
884 size_t total = 0;
885 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
886 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
887 space::ContinuousSpace* space = *it;
888 if (space->IsDlMallocSpace()) {
889 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700890 }
891 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700892 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
893 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
894 space::DiscontinuousSpace* space = *it;
895 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
896 }
897 return total;
898}
899
900size_t Heap::GetBytesAllocatedEver() const {
901 size_t total = 0;
902 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
903 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
904 space::ContinuousSpace* space = *it;
905 if (space->IsDlMallocSpace()) {
906 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
907 }
908 }
909 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
910 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
911 space::DiscontinuousSpace* space = *it;
912 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
913 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700914 return total;
915}
916
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700917class InstanceCounter {
918 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800919 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700920 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800921 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700922 }
923
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800924 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800925 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800926 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800927 if (use_is_assignable_from_) {
928 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
929 ++counts_[i];
930 }
931 } else {
932 if (instance_class == classes_[i]) {
933 ++counts_[i];
934 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700935 }
936 }
937 }
938
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700939 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800940 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800941 bool use_is_assignable_from_;
942 uint64_t* const counts_;
943
944 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700945};
946
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800947void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800948 uint64_t* counts) {
949 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
950 // is empty, so the live bitmap is the only place we need to look.
951 Thread* self = Thread::Current();
952 self->TransitionFromRunnableToSuspended(kNative);
953 CollectGarbage(false);
954 self->TransitionFromSuspendedToRunnable();
955
956 InstanceCounter counter(classes, use_is_assignable_from, counts);
957 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700958 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700959}
960
Elliott Hughes3b78c942013-01-15 17:35:41 -0800961class InstanceCollector {
962 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800963 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800964 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
965 : class_(c), max_count_(max_count), instances_(instances) {
966 }
967
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800968 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
969 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800970 if (instance_class == class_) {
971 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800972 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800973 }
974 }
975 }
976
977 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800978 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800979 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800980 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800981
982 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
983};
984
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800985void Heap::GetInstances(mirror::Class* c, int32_t max_count,
986 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800987 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
988 // is empty, so the live bitmap is the only place we need to look.
989 Thread* self = Thread::Current();
990 self->TransitionFromRunnableToSuspended(kNative);
991 CollectGarbage(false);
992 self->TransitionFromSuspendedToRunnable();
993
994 InstanceCollector collector(c, max_count, instances);
995 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
996 GetLiveBitmap()->Visit(collector);
997}
998
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800999class ReferringObjectsFinder {
1000 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001001 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1002 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001003 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1004 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1005 }
1006
1007 // For bitmap Visit.
1008 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1009 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001010 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001011 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001012 }
1013
1014 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001015 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
1016 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001017 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001018 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001019 }
1020 }
1021
1022 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001023 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001024 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001025 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001026
1027 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1028};
1029
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001030void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1031 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001032 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1033 // is empty, so the live bitmap is the only place we need to look.
1034 Thread* self = Thread::Current();
1035 self->TransitionFromRunnableToSuspended(kNative);
1036 CollectGarbage(false);
1037 self->TransitionFromSuspendedToRunnable();
1038
1039 ReferringObjectsFinder finder(o, max_count, referring_objects);
1040 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1041 GetLiveBitmap()->Visit(finder);
1042}
1043
Ian Rogers30fab402012-01-23 15:43:46 -08001044void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001045 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1046 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001047 Thread* self = Thread::Current();
1048 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001049 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001050}
1051
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001052void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001053 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001054 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1055 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001056 Thread* self = Thread::Current();
1057 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001058
1059 // Try to see if we have any Zygote spaces.
1060 if (have_zygote_space_) {
1061 return;
1062 }
1063
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001064 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1065
1066 {
1067 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001068 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001069 FlushAllocStack();
1070 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001071
Ian Rogers1d54e732013-05-02 21:10:01 -07001072 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1073 // of the remaining available heap memory.
1074 space::DlMallocSpace* zygote_space = alloc_space_;
1075 alloc_space_ = zygote_space->CreateZygoteSpace();
1076 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001077
Ian Rogers1d54e732013-05-02 21:10:01 -07001078 // Change the GC retention policy of the zygote space to only collect when full.
1079 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1080 AddContinuousSpace(alloc_space_);
1081 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001082
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001083 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001084 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -07001085 typedef std::vector<collector::MarkSweep*>::const_iterator It;
1086 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1087 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001088 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001089 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001090}
1091
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001092void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001093 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1094 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001095 allocation_stack_->Reset();
1096}
1097
Ian Rogers1d54e732013-05-02 21:10:01 -07001098void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1099 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001100 mirror::Object** limit = stack->End();
1101 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1102 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001103 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001104 if (LIKELY(bitmap->HasAddress(obj))) {
1105 bitmap->Set(obj);
1106 } else {
1107 large_objects->Set(obj);
1108 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001109 }
1110}
1111
Ian Rogers1d54e732013-05-02 21:10:01 -07001112void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1113 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001114 mirror::Object** limit = stack->End();
1115 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1116 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001117 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001118 if (LIKELY(bitmap->HasAddress(obj))) {
1119 bitmap->Clear(obj);
1120 } else {
1121 large_objects->Clear(obj);
1122 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001123 }
1124}
1125
Ian Rogers1d54e732013-05-02 21:10:01 -07001126collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1127 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001128 Thread* self = Thread::Current();
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001129
1130 switch (gc_cause) {
1131 case kGcCauseForAlloc:
1132 ATRACE_BEGIN("GC (alloc)");
1133 break;
1134 case kGcCauseBackground:
1135 ATRACE_BEGIN("GC (background)");
1136 break;
1137 case kGcCauseExplicit:
1138 ATRACE_BEGIN("GC (explicit)");
1139 break;
1140 }
1141
Mathieu Chartier65db8802012-11-20 12:36:46 -08001142 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001143 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001144
Ian Rogers120f1c72012-09-28 17:17:10 -07001145 if (self->IsHandlingStackOverflow()) {
1146 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1147 }
1148
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001149 // Ensure there is only one GC at a time.
1150 bool start_collect = false;
1151 while (!start_collect) {
1152 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001153 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001154 if (!is_gc_running_) {
1155 is_gc_running_ = true;
1156 start_collect = true;
1157 }
1158 }
1159 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001160 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001161 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1162 // Not doing at the moment to ensure soft references are cleared.
1163 }
1164 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001165 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001166
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001167 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1168 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1169 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1170 }
1171
Ian Rogers1d54e732013-05-02 21:10:01 -07001172 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001173 uint64_t gc_start_size = GetBytesAllocated();
1174 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001175 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001176 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1177 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001178 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001179 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001180 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001181 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1182 }
1183
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001184 if (gc_type == collector::kGcTypeSticky &&
1185 alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
1186 gc_type = collector::kGcTypePartial;
1187 }
1188
Ian Rogers1d54e732013-05-02 21:10:01 -07001189 DCHECK_LT(gc_type, collector::kGcTypeMax);
1190 DCHECK_NE(gc_type, collector::kGcTypeNone);
1191 collector::MarkSweep* collector = NULL;
1192 typedef std::vector<collector::MarkSweep*>::iterator It;
1193 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1194 it != end; ++it) {
1195 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001196 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1197 collector = cur_collector;
1198 break;
1199 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001200 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001201 CHECK(collector != NULL)
1202 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1203 << " and type=" << gc_type;
1204 collector->clear_soft_references_ = clear_soft_references;
1205 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001206 total_objects_freed_ever_ += collector->GetFreedObjects();
1207 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001208
Ian Rogers1d54e732013-05-02 21:10:01 -07001209 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001210 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1211 bool was_slow = duration > kSlowGcThreshold ||
1212 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1213 for (size_t i = 0; i < pauses.size(); ++i) {
1214 if (pauses[i] > kLongGcPauseThreshold) {
1215 was_slow = true;
1216 }
1217 }
1218
1219 if (was_slow) {
1220 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001221 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001222 const size_t total_memory = GetTotalMemory();
1223 std::ostringstream pause_string;
1224 for (size_t i = 0; i < pauses.size(); ++i) {
1225 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1226 << ((i != pauses.size() - 1) ? ", " : "");
1227 }
1228 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001229 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1230 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1231 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1232 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001233 if (VLOG_IS_ON(heap)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001234 LOG(INFO) << Dumpable<base::NewTimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001235 }
1236 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001237
Ian Rogers15bf2d32012-08-28 17:33:04 -07001238 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001239 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001240 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001241 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001242 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001243 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001244 }
1245 // Inform DDMS that a GC completed.
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001246 ATRACE_END();
Ian Rogers15bf2d32012-08-28 17:33:04 -07001247 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001248 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001249}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001250
Ian Rogers1d54e732013-05-02 21:10:01 -07001251void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::NewTimingLogger& timings,
1252 collector::GcType gc_type) {
1253 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001254 // Don't need to do anything for mod union table in this case since we are only scanning dirty
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001255 // cards.
1256 return;
1257 }
1258
1259 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001260 if (gc_type == collector::kGcTypePartial) {
1261 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001262 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001263
Ian Rogers1d54e732013-05-02 21:10:01 -07001264 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001265 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001266 }
1267
1268 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001269 timings.NewSplit("UpdateModUnionTable");
1270 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001271
1272 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001273 timings.NewSplit("MarkImageToAllocSpaceReferences");
1274 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001275}
1276
Ian Rogers1d54e732013-05-02 21:10:01 -07001277static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001278 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001279 if (root == obj) {
1280 LOG(INFO) << "Object " << obj << " is a root";
1281 }
1282}
1283
1284class ScanVisitor {
1285 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001286 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001287 LOG(INFO) << "Would have rescanned object " << obj;
1288 }
1289};
1290
Ian Rogers1d54e732013-05-02 21:10:01 -07001291// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001292class VerifyReferenceVisitor {
1293 public:
Ian Rogers1d54e732013-05-02 21:10:01 -07001294 VerifyReferenceVisitor(Heap* heap)
1295 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
1296 : heap_(heap), failed_(false) {
1297 }
1298
1299 bool Failed() const {
1300 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001301 }
1302
1303 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001304 // analysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001305 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
Ian Rogers1d54e732013-05-02 21:10:01 -07001306 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001307 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001308 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001309 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1310 accounting::CardTable* card_table = heap_->GetCardTable();
1311 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1312 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001313
Ian Rogers1d54e732013-05-02 21:10:01 -07001314 if (obj != NULL) {
1315 byte* card_addr = card_table->CardFromAddr(obj);
1316 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1317 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1318 << "\nObj type " << PrettyTypeOf(obj)
1319 << "\nRef type " << PrettyTypeOf(ref);
1320 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1321 void* cover_begin = card_table->AddrFromCard(card_addr);
1322 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1323 accounting::CardTable::kCardSize);
1324 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1325 << "-" << cover_end;
1326 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001327
Ian Rogers1d54e732013-05-02 21:10:01 -07001328 // Print out how the object is live.
1329 if (bitmap != NULL && bitmap->Test(obj)) {
1330 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1331 }
1332 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
1333 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1334 }
1335 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
1336 LOG(ERROR) << "Object " << obj << " found in live stack";
1337 }
1338 // Attempt to see if the card table missed the reference.
1339 ScanVisitor scan_visitor;
1340 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1341 card_table->Scan(bitmap, byte_cover_begin,
1342 byte_cover_begin + accounting::CardTable::kCardSize,
1343 scan_visitor, VoidFunctor());
1344
1345 // Search to see if any of the roots reference our object.
1346 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1347 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1348
1349 // Search to see if any of the roots reference our reference.
1350 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1351 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1352 } else {
1353 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001354 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001355 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1356 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001357 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001358 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001359 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001360 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001361 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1362 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1363 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001364 }
1365 }
1366
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001367 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001368 return heap_->IsLiveObjectLocked(obj);
1369 }
1370
1371 static void VerifyRoots(const mirror::Object* root, void* arg) {
1372 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1373 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001374 }
1375
1376 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001377 Heap* const heap_;
1378 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001379};
1380
Ian Rogers1d54e732013-05-02 21:10:01 -07001381// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001382class VerifyObjectVisitor {
1383 public:
Ian Rogers1d54e732013-05-02 21:10:01 -07001384 VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001385 }
1386
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001387 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001388 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001389 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1390 // be live or else how did we find it in the live bitmap?
1391 VerifyReferenceVisitor visitor(heap_);
1392 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1393 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001394 }
1395
1396 bool Failed() const {
1397 return failed_;
1398 }
1399
1400 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001401 Heap* const heap_;
1402 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001403};
1404
1405// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001406bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001407 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001408 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001409 allocation_stack_->Sort();
1410 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001411 // Perform the verification.
1412 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001413 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001414 GetLiveBitmap()->Visit(visitor);
1415 // We don't want to verify the objects in the allocation stack since they themselves may be
1416 // pointing to dead objects if they are not reachable.
1417 if (visitor.Failed()) {
1418 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001419 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001420 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001421 return true;
1422}
1423
1424class VerifyReferenceCardVisitor {
1425 public:
1426 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1427 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1428 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001429 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001430 }
1431
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001432 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1433 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001434 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1435 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001436 // Filter out class references since changing an object's class does not mark the card as dirty.
1437 // Also handles large objects, since the only reference they hold is a class reference.
1438 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001439 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001440 // If the object is not dirty and it is referencing something in the live stack other than
1441 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001442 if (!card_table->AddrIsInCardTable(obj)) {
1443 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1444 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001445 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001446 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1447 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001448 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
1449 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1450 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001451 LOG(ERROR) << "Object " << obj << " found in live stack";
1452 }
1453 if (heap_->GetLiveBitmap()->Test(obj)) {
1454 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1455 }
1456 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1457 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1458
1459 // Print which field of the object is dead.
1460 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001461 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001462 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001463 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1464 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001465 CHECK(fields != NULL);
1466 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001467 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001468 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1469 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1470 << PrettyField(cur);
1471 break;
1472 }
1473 }
1474 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001475 const mirror::ObjectArray<mirror::Object>* object_array =
1476 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001477 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1478 if (object_array->Get(i) == ref) {
1479 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1480 }
1481 }
1482 }
1483
1484 *failed_ = true;
1485 }
1486 }
1487 }
1488 }
1489
1490 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001491 Heap* const heap_;
1492 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001493};
1494
1495class VerifyLiveStackReferences {
1496 public:
1497 VerifyLiveStackReferences(Heap* heap)
1498 : heap_(heap),
1499 failed_(false) {
1500
1501 }
1502
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001503 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001504 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1505 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001506 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001507 }
1508
1509 bool Failed() const {
1510 return failed_;
1511 }
1512
1513 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001514 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001515 bool failed_;
1516};
1517
1518bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001519 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001520
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001521 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001522 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001523 VerifyLiveStackReferences visitor(this);
1524 GetLiveBitmap()->Visit(visitor);
1525
1526 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001527 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001528 visitor(*it);
1529 }
1530
1531 if (visitor.Failed()) {
1532 DumpSpaces();
1533 return false;
1534 }
1535 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001536}
1537
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001538void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001539 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001540
1541 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001542 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001543 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001544 }
1545}
1546
Ian Rogers1d54e732013-05-02 21:10:01 -07001547void Heap::ProcessCards(base::NewTimingLogger& timings) {
1548 // Clear cards and keep track of cards cleared in the mod-union table.
1549 typedef std::vector<space::ContinuousSpace*>::iterator It;
1550 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1551 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001552 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001553 timings.NewSplit("ModUnionClearCards");
1554 image_mod_union_table_->ClearCards(space);
1555 } else if (space->IsZygoteSpace()) {
1556 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001557 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001558 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001559 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1560 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001561 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001562 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001563 }
1564 }
1565}
1566
Ian Rogers1d54e732013-05-02 21:10:01 -07001567void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001568 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1569 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001570
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001571 if (verify_pre_gc_heap_) {
1572 thread_list->SuspendAll();
1573 {
1574 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1575 if (!VerifyHeapReferences()) {
1576 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1577 }
1578 }
1579 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001580 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001581
1582 // Check that all objects which reference things in the live stack are on dirty cards.
1583 if (verify_missing_card_marks_) {
1584 thread_list->SuspendAll();
1585 {
1586 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1587 SwapStacks();
1588 // Sort the live stack so that we can quickly binary search it later.
1589 if (!VerifyMissingCardMarks()) {
1590 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1591 }
1592 SwapStacks();
1593 }
1594 thread_list->ResumeAll();
1595 }
1596
1597 if (verify_mod_union_table_) {
1598 thread_list->SuspendAll();
1599 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1600 zygote_mod_union_table_->Update();
1601 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001602 image_mod_union_table_->Update();
1603 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001604 thread_list->ResumeAll();
1605 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001606}
1607
Ian Rogers1d54e732013-05-02 21:10:01 -07001608void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001609 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001610
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001611 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1612 // reachable objects.
1613 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001614 Thread* self = Thread::Current();
1615 CHECK_NE(self->GetState(), kRunnable);
1616 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001617 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001618 {
1619 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1620 // Swapping bound bitmaps does nothing.
1621 gc->SwapBitmaps();
1622 if (!VerifyHeapReferences()) {
1623 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1624 }
1625 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001626 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001627 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001628 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001629 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001630}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001631
Ian Rogers1d54e732013-05-02 21:10:01 -07001632void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001633 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001634
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001635 if (verify_system_weaks_) {
1636 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001637 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001638 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001639 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001640}
1641
Ian Rogers1d54e732013-05-02 21:10:01 -07001642collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1643 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001644 if (concurrent_gc_) {
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001645 ATRACE_BEGIN("GC: Wait For Concurrent");
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001646 bool do_wait;
1647 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001648 {
1649 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001650 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001651 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001652 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001653 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001654 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001655 // We must wait, change thread state then sleep on gc_complete_cond_;
1656 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1657 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001658 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001659 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001660 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001661 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001662 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001663 wait_time = NanoTime() - wait_start;;
1664 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001665 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001666 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001667 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1668 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001669 }
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001670 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001671 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001672 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001673}
1674
Elliott Hughesc967f782012-04-16 10:23:15 -07001675void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001676 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001677 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001678 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001679}
1680
1681size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001682 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001683}
1684
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001685void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001686 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001687 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001688 << PrettySize(GetMaxMemory());
1689 max_allowed_footprint = GetMaxMemory();
1690 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001691 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001692}
1693
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001694void Heap::UpdateMaxNativeFootprint() {
1695 size_t native_size = native_bytes_allocated_;
1696 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
1697 size_t target_size = native_size / GetTargetHeapUtilization();
1698 if (target_size > native_size + max_free_) {
1699 target_size = native_size + max_free_;
1700 } else if (target_size < native_size + min_free_) {
1701 target_size = native_size + min_free_;
1702 }
1703 native_footprint_gc_watermark_ = target_size;
1704 native_footprint_limit_ = 2 * target_size - native_size;
1705}
1706
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001707void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001708 // We know what our utilization is at this moment.
1709 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001710 const size_t bytes_allocated = GetBytesAllocated();
1711 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001712 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001713
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001714 size_t target_size;
1715 if (gc_type != collector::kGcTypeSticky) {
1716 // Grow the heap for non sticky GC.
1717 target_size = bytes_allocated / GetTargetHeapUtilization();
1718 if (target_size > bytes_allocated + max_free_) {
1719 target_size = bytes_allocated + max_free_;
1720 } else if (target_size < bytes_allocated + min_free_) {
1721 target_size = bytes_allocated + min_free_;
1722 }
1723 next_gc_type_ = collector::kGcTypeSticky;
1724 } else {
1725 // Based on how close the current heap size is to the target size, decide
1726 // whether or not to do a partial or sticky GC next.
1727 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
1728 next_gc_type_ = collector::kGcTypeSticky;
1729 } else {
1730 next_gc_type_ = collector::kGcTypePartial;
1731 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001732
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001733 // If we have freed enough memory, shrink the heap back down.
1734 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
1735 target_size = bytes_allocated + max_free_;
1736 } else {
1737 target_size = std::max(bytes_allocated, max_allowed_footprint_);
1738 }
1739 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001740 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001741
Ian Rogers1d54e732013-05-02 21:10:01 -07001742 // Calculate when to perform the next ConcurrentGC.
1743 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001744 // Calculate the estimated GC duration.
1745 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1746 // Estimate how many remaining bytes we will have when we need to start the next GC.
1747 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001748 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1749 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1750 // A never going to happen situation that from the estimated allocation rate we will exceed
1751 // the applications entire footprint with the given estimated allocation rate. Schedule
1752 // another GC straight away.
1753 concurrent_start_bytes_ = bytes_allocated;
1754 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001755 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1756 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1757 // right away.
1758 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001759 }
1760 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1761 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1762 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001763
1764 UpdateMaxNativeFootprint();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001765}
1766
jeffhaoc1160702011-10-27 15:48:45 -07001767void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001768 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001769 alloc_space_->ClearGrowthLimit();
1770}
1771
Elliott Hughesadb460d2011-10-05 17:02:34 -07001772void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001773 MemberOffset reference_queue_offset,
1774 MemberOffset reference_queueNext_offset,
1775 MemberOffset reference_pendingNext_offset,
1776 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001777 reference_referent_offset_ = reference_referent_offset;
1778 reference_queue_offset_ = reference_queue_offset;
1779 reference_queueNext_offset_ = reference_queueNext_offset;
1780 reference_pendingNext_offset_ = reference_pendingNext_offset;
1781 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1782 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1783 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1784 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1785 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1786 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1787}
1788
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001789mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001790 DCHECK(reference != NULL);
1791 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001792 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001793}
1794
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001795void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001796 DCHECK(reference != NULL);
1797 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1798 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1799}
1800
1801// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001802bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001803 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001804 const mirror::Object* queue =
1805 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1806 const mirror::Object* queue_next =
1807 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001808 return (queue != NULL) && (queue_next == NULL);
1809}
1810
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001811void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001812 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001813 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1814 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001815 EnqueuePendingReference(ref, cleared_reference_list);
1816}
1817
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001818void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001819 DCHECK(ref != NULL);
1820 DCHECK(list != NULL);
1821
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001822 // TODO: Remove this lock, use atomic stacks for storing references.
1823 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001824 if (*list == NULL) {
1825 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1826 *list = ref;
1827 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001828 mirror::Object* head =
1829 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001830 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1831 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1832 }
1833}
1834
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001835mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001836 DCHECK(list != NULL);
1837 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001838 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1839 false);
1840 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001841
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001842 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1843 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001844 if (*list == head) {
1845 ref = *list;
1846 *list = NULL;
1847 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001848 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1849 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001850 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1851 ref = head;
1852 }
1853 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1854 return ref;
1855}
1856
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001857void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001858 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001859 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001860 ArgArray arg_array(NULL, 0);
1861 arg_array.Append(reinterpret_cast<uint32_t>(object));
1862 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001863 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001864}
1865
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001866void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001867 DCHECK(cleared != NULL);
1868 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001869 // When a runtime isn't started there are no reference queues to care about so ignore.
1870 if (LIKELY(Runtime::Current()->IsStarted())) {
1871 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001872 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001873 ArgArray arg_array(NULL, 0);
1874 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1875 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001876 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001877 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001878 *cleared = NULL;
1879 }
1880}
1881
Ian Rogers1f539342012-10-03 21:09:42 -07001882void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001883 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001884 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001885 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001886 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001887 !runtime->IsConcurrentGcEnabled()) {
1888 return;
1889 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001890 {
1891 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1892 if (runtime->IsShuttingDown()) {
1893 return;
1894 }
1895 }
1896 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001897 return;
1898 }
1899
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001900 // We already have a request pending, no reason to start more until we update
1901 // concurrent_start_bytes_.
1902 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1903
Ian Rogers120f1c72012-09-28 17:17:10 -07001904 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001905 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1906 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001907 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1908 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001909 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001910}
1911
Ian Rogers81d425b2012-09-27 16:03:43 -07001912void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001913 {
1914 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001915 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001916 return;
1917 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001918 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001919
Mathieu Chartier65db8802012-11-20 12:36:46 -08001920 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001921 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001922 CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001923 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001924}
1925
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001926void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001927 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1928 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1929 // a space it will hold its lock and can become a cause of jank.
1930 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1931 // forking.
1932
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001933 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1934 // because that only marks object heads, so a large array looks like lots of empty space. We
1935 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1936 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1937 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1938 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001939 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001940 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001941 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1942 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001943 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1944 // heap trim occurred in the last two seconds.
1945 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001946 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001947
1948 Thread* self = Thread::Current();
1949 {
1950 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1951 Runtime* runtime = Runtime::Current();
1952 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1953 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1954 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1955 // as we don't hold the lock while requesting the trim).
1956 return;
1957 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001958 }
Ian Rogers48931882013-01-22 14:35:16 -08001959
1960 SchedPolicy policy;
1961 get_sched_policy(self->GetTid(), &policy);
1962 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1963 // Don't trim the heap if we are a foreground or audio app.
1964 return;
1965 }
1966
Ian Rogers1d54e732013-05-02 21:10:01 -07001967 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001968 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001969 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1970 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001971 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1972 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001973 CHECK(!env->ExceptionCheck());
1974}
1975
Ian Rogers48931882013-01-22 14:35:16 -08001976size_t Heap::Trim() {
1977 // Handle a requested heap trim on a thread outside of the main GC thread.
1978 return alloc_space_->Trim();
1979}
1980
Mathieu Chartier987ccff2013-07-08 11:05:21 -07001981bool Heap::IsGCRequestPending() const {
1982 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
1983}
1984
1985void Heap::RegisterNativeAllocation(int bytes) {
1986 // Total number of native bytes allocated.
1987 native_bytes_allocated_ += bytes;
1988 Thread* self = Thread::Current();
1989 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
1990 // The second watermark is higher than the gc watermark. If you hit this it means you are
1991 // allocating native objects faster than the GC can keep up with.
1992 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
1993 JNIEnv* env = self->GetJniEnv();
1994 // Can't do this in WellKnownClasses::Init since System is not properly set up at that
1995 // point.
1996 if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
1997 DCHECK(WellKnownClasses::java_lang_System != NULL);
1998 WellKnownClasses::java_lang_System_runFinalization =
1999 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2000 assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
2001 }
2002 if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
2003 // Just finished a GC, attempt to run finalizers.
2004 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2005 WellKnownClasses::java_lang_System_runFinalization);
2006 CHECK(!env->ExceptionCheck());
2007 }
2008
2009 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2010 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2011 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
2012 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2013 WellKnownClasses::java_lang_System_runFinalization);
2014 CHECK(!env->ExceptionCheck());
2015 }
2016 // We have just run finalizers, update the native watermark since it is very likely that
2017 // finalizers released native managed allocations.
2018 UpdateMaxNativeFootprint();
2019 } else {
2020 if (!IsGCRequestPending()) {
2021 RequestConcurrentGC(self);
2022 }
2023 }
2024 }
2025}
2026
2027void Heap::RegisterNativeFree(int bytes) {
2028 int expected_size, new_size;
2029 do {
2030 expected_size = native_bytes_allocated_.get();
2031 new_size = expected_size - bytes;
2032 if (new_size < 0) {
2033 ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
2034 bytes, expected_size);
2035 break;
2036 }
2037 } while (!native_bytes_allocated_.CompareAndSwap(expected_size, new_size));
2038}
2039
Ian Rogers1d54e732013-05-02 21:10:01 -07002040} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002041} // namespace art