blob: 34c0b5c058e8c8dc0af7ad77da5ef0bbdb9f9dc7 [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
Brian Carlstrom5643b782012-02-05 12:32:53 -080019#include <sys/types.h>
20#include <sys/wait.h>
21
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070023#include <vector>
24
Elliott Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/stl_util.h"
Ian Rogers48931882013-01-22 14:35:16 -080026#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070027#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070028#include "gc/accounting/atomic_stack.h"
29#include "gc/accounting/card_table-inl.h"
30#include "gc/accounting/heap_bitmap-inl.h"
31#include "gc/accounting/mod_union_table-inl.h"
32#include "gc/accounting/space_bitmap-inl.h"
33#include "gc/collector/mark_sweep-inl.h"
34#include "gc/collector/partial_mark_sweep.h"
35#include "gc/collector/sticky_mark_sweep.h"
36#include "gc/space/image_space.h"
37#include "gc/space/large_object_space.h"
38#include "gc/space/space-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070039#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080040#include "invoke_arg_array_builder.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mirror/class-inl.h"
42#include "mirror/field-inl.h"
43#include "mirror/object.h"
44#include "mirror/object-inl.h"
45#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080046#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080047#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070048#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070049#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070050#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070051#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070052#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070053#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070054
55namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070056namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070057
Ian Rogers1d54e732013-05-02 21:10:01 -070058// When to create a log message about a slow GC, 100ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080059static const uint64_t kSlowGcThreshold = MsToNs(100);
Ian Rogers1d54e732013-05-02 21:10:01 -070060// When to create a log message about a slow pause, 5ms.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080061static const uint64_t kLongGcPauseThreshold = MsToNs(5);
Mathieu Chartier65db8802012-11-20 12:36:46 -080062static const bool kDumpGcPerformanceOnShutdown = false;
Ian Rogers1d54e732013-05-02 21:10:01 -070063// Minimum amount of remaining bytes before a concurrent GC is triggered.
64static const size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070065const double Heap::kDefaultTargetUtilization = 0.5;
66
Elliott Hughesae80b492012-04-24 10:43:17 -070067static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080068 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080069 std::vector<std::string> boot_class_path;
70 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070071 if (boot_class_path.empty()) {
72 LOG(FATAL) << "Failed to generate image because no boot class path specified";
73 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080074
75 std::vector<char*> arg_vector;
76
77 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070078 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080079 const char* dex2oat = dex2oat_string.c_str();
80 arg_vector.push_back(strdup(dex2oat));
81
82 std::string image_option_string("--image=");
83 image_option_string += image_file_name;
84 const char* image_option = image_option_string.c_str();
85 arg_vector.push_back(strdup(image_option));
86
87 arg_vector.push_back(strdup("--runtime-arg"));
88 arg_vector.push_back(strdup("-Xms64m"));
89
90 arg_vector.push_back(strdup("--runtime-arg"));
91 arg_vector.push_back(strdup("-Xmx64m"));
92
93 for (size_t i = 0; i < boot_class_path.size(); i++) {
94 std::string dex_file_option_string("--dex-file=");
95 dex_file_option_string += boot_class_path[i];
96 const char* dex_file_option = dex_file_option_string.c_str();
97 arg_vector.push_back(strdup(dex_file_option));
98 }
99
100 std::string oat_file_option_string("--oat-file=");
101 oat_file_option_string += image_file_name;
102 oat_file_option_string.erase(oat_file_option_string.size() - 3);
103 oat_file_option_string += "oat";
104 const char* oat_file_option = oat_file_option_string.c_str();
105 arg_vector.push_back(strdup(oat_file_option));
106
jeffhao8161c032012-10-31 15:50:00 -0700107 std::string base_option_string(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
108 arg_vector.push_back(strdup(base_option_string.c_str()));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800109
Brian Carlstrom265091e2013-01-30 14:08:26 -0800110 if (!kIsTargetBuild) {
111 arg_vector.push_back(strdup("--host"));
112 }
113
Elliott Hughes48436bb2012-02-07 15:23:28 -0800114 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800115 LOG(INFO) << command_line;
116
Elliott Hughes48436bb2012-02-07 15:23:28 -0800117 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800118 char** argv = &arg_vector[0];
119
120 // fork and exec dex2oat
121 pid_t pid = fork();
122 if (pid == 0) {
123 // no allocation allowed between fork and exec
124
125 // change process groups, so we don't get reaped by ProcessManager
126 setpgid(0, 0);
127
128 execv(dex2oat, argv);
129
130 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
131 return false;
132 } else {
133 STLDeleteElements(&arg_vector);
134
135 // wait for dex2oat to finish
136 int status;
137 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
138 if (got_pid != pid) {
139 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
140 return false;
141 }
142 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
143 LOG(ERROR) << dex2oat << " failed: " << command_line;
144 return false;
145 }
146 }
147 return true;
148}
149
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700150void Heap::UnReserveOatFileAddressRange() {
151 oat_file_map_.reset(NULL);
152}
153
Mathieu Chartier0051be62012-10-12 17:47:11 -0700154Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
155 double target_utilization, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700156 const std::string& original_image_file_name, bool concurrent_gc)
157 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800158 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700159 concurrent_gc_(concurrent_gc),
160 have_zygote_space_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -0700161 reference_queue_lock_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800162 is_gc_running_(false),
Ian Rogers1d54e732013-05-02 21:10:01 -0700163 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800164 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700165 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700166 max_allowed_footprint_(initial_size),
Ian Rogers1d54e732013-05-02 21:10:01 -0700167 concurrent_start_bytes_(concurrent_gc ? initial_size - (kMinConcurrentRemainingBytes)
168 : std::numeric_limits<size_t>::max()),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700169 sticky_gc_count_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -0700170 sticky_to_partial_gc_ratio_(10),
171 total_bytes_freed_ever_(0),
172 total_objects_freed_ever_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700173 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800174 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700175 verify_missing_card_marks_(false),
176 verify_system_weaks_(false),
177 verify_pre_gc_heap_(false),
178 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700179 verify_mod_union_table_(false),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700180 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700181 min_remaining_space_for_sticky_gc_(1 * MB),
Ian Rogers1d54e732013-05-02 21:10:01 -0700182 last_trim_time_ms_(0),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800183 allocation_rate_(0),
Ian Rogers1d54e732013-05-02 21:10:01 -0700184 max_allocation_stack_size_(kDesiredHeapVerification > kNoHeapVerification? KB : MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800185 reference_referent_offset_(0),
186 reference_queue_offset_(0),
187 reference_queueNext_offset_(0),
188 reference_pendingNext_offset_(0),
189 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700190 min_free_(min_free),
191 max_free_(max_free),
192 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700193 total_wait_time_(0),
194 measure_allocation_time_(false),
195 total_allocation_time_(0),
Ian Rogers04d7aa92013-03-16 14:29:17 -0700196 verify_object_mode_(kHeapVerificationNotPermitted) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800197 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800198 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700199 }
200
Ian Rogers1d54e732013-05-02 21:10:01 -0700201 live_bitmap_.reset(new accounting::HeapBitmap(this));
202 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700203
Ian Rogers30fab402012-01-23 15:43:46 -0800204 // Requested begin for the alloc space, to follow the mapped image and oat files
205 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800206 std::string image_file_name(original_image_file_name);
207 if (!image_file_name.empty()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700208 space::ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700209
Brian Carlstrom5643b782012-02-05 12:32:53 -0800210 if (OS::FileExists(image_file_name.c_str())) {
211 // If the /system file exists, it should be up-to-date, don't try to generate
Ian Rogers1d54e732013-05-02 21:10:01 -0700212 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800213 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -0700214 // If the /system file didn't exist, we need to use one from the dalvik-cache.
Brian Carlstrom5643b782012-02-05 12:32:53 -0800215 // If the cache file exists, try to open, but if it fails, regenerate.
216 // If it does not exist, generate.
Brian Carlstrom7675e162013-06-10 16:18:04 -0700217 image_file_name = GetDalvikCacheFilenameOrDie(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800218 if (OS::FileExists(image_file_name.c_str())) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700219 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800220 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700221 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700222 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700223 image_space = space::ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800224 }
225 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700226
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700227 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Ian Rogers1d54e732013-05-02 21:10:01 -0700228 AddContinuousSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800229 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
230 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800231 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
232 CHECK_GT(oat_file_end_addr, image_space->End());
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700233
234 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
235 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800236 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr), kPageSize);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700237 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
238 reinterpret_cast<byte*>(reserve_begin),
Ian Rogers10c5b782013-01-10 10:40:53 -0800239 reserve_end - reserve_begin, PROT_NONE));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700240
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800241 if (oat_file_end_addr > requested_begin) {
242 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700243 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700244 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700245 }
246
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700247 // Allocate the large object space.
Ian Rogers22a20862013-03-16 16:34:57 -0700248 const bool kUseFreeListSpaceForLOS = false;
249 if (kUseFreeListSpaceForLOS) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700250 large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
Ian Rogers22a20862013-03-16 16:34:57 -0700251 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700252 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
Ian Rogers22a20862013-03-16 16:34:57 -0700253 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700254 CHECK(large_object_space_ != NULL) << "Failed to create large object space";
255 AddDiscontinuousSpace(large_object_space_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700256
Ian Rogers1d54e732013-05-02 21:10:01 -0700257 alloc_space_ = space::DlMallocSpace::Create("alloc space",
258 initial_size,
259 growth_limit, capacity,
260 requested_begin);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700261 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
jeffhao8161c032012-10-31 15:50:00 -0700262 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Ian Rogers1d54e732013-05-02 21:10:01 -0700263 AddContinuousSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700264
Ian Rogers1d54e732013-05-02 21:10:01 -0700265 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
266 byte* heap_begin = continuous_spaces_.front()->Begin();
267 size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
268 if (continuous_spaces_.back()->IsDlMallocSpace()) {
269 heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700270 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700271
Ian Rogers30fab402012-01-23 15:43:46 -0800272 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700273 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -0700274 typedef std::vector<space::ContinuousSpace*>::iterator It;
275 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
276 space::ContinuousSpace* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800277 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700278 space::ImageSpace* image_space = space->AsImageSpace();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700279 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800280 }
281 }
282
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800283 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700284 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700285 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700286
Ian Rogers1d54e732013-05-02 21:10:01 -0700287 image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
288 CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700289
Ian Rogers1d54e732013-05-02 21:10:01 -0700290 zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700291 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700292
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700293 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700294 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700295
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800296 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700297 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700298 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
299 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
300 max_allocation_stack_size_));
301 live_stack_.reset(accounting::ObjectStack::Create("live stack",
302 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700303
Mathieu Chartier65db8802012-11-20 12:36:46 -0800304 // It's still too early to take a lock because there are no threads yet, but we can create locks
305 // now. We don't create it earlier to make it clear that you can't use locks during heap
306 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700307 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700308 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
309 *gc_complete_lock_));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700310
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700311 // Create the reference queue lock, this is required so for parrallel object scanning in the GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700312 reference_queue_lock_ = new Mutex("reference queue lock");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700313
Ian Rogers1d54e732013-05-02 21:10:01 -0700314 last_gc_time_ns_ = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -0800315 last_gc_size_ = GetBytesAllocated();
316
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800317 // Create our garbage collectors.
318 for (size_t i = 0; i < 2; ++i) {
319 const bool concurrent = i != 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700320 mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
321 mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
322 mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700323 }
324
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800325 CHECK(max_allowed_footprint_ != 0);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800326 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800327 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700328 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700329}
330
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700331void Heap::CreateThreadPool() {
332 // TODO: Make sysconf(_SC_NPROCESSORS_CONF) be a helper function?
333 // Use the number of processors - 1 since the thread doing the GC does work while its waiting for
334 // workers to complete.
Ian Rogers1d54e732013-05-02 21:10:01 -0700335 thread_pool_.reset(new ThreadPool(1)); // new ThreadPool(sysconf(_SC_NPROCESSORS_CONF) - 1));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700336}
337
338void Heap::DeleteThreadPool() {
339 thread_pool_.reset(NULL);
340}
341
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700342// Sort spaces based on begin address
Ian Rogers1d54e732013-05-02 21:10:01 -0700343struct ContinuousSpaceSorter {
344 bool operator ()(const space::ContinuousSpace* a, const space::ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700345 return a->Begin() < b->Begin();
346 }
347};
348
Ian Rogers1d54e732013-05-02 21:10:01 -0700349void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700350 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700351 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700352 DCHECK(space->GetLiveBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700353 live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700354 DCHECK(space->GetMarkBitmap() != NULL);
Ian Rogers1d54e732013-05-02 21:10:01 -0700355 mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
356 continuous_spaces_.push_back(space);
357 if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
358 alloc_space_ = space->AsDlMallocSpace();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700359 }
360
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700361 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
Ian Rogers1d54e732013-05-02 21:10:01 -0700362 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(), ContinuousSpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700363
364 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
365 // avoid redundant marking.
366 bool seen_zygote = false, seen_alloc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700367 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
368 for (It it = continuous_spaces_.begin(); it != continuous_spaces_.end(); ++it) {
369 space::ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700370 if (space->IsImageSpace()) {
371 DCHECK(!seen_zygote);
372 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700373 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700374 DCHECK(!seen_alloc);
375 seen_zygote = true;
Ian Rogers1d54e732013-05-02 21:10:01 -0700376 } else if (space->IsDlMallocSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700377 seen_alloc = true;
378 }
379 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800380}
381
Ian Rogers1d54e732013-05-02 21:10:01 -0700382void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
383 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
384 DCHECK(space != NULL);
385 DCHECK(space->GetLiveObjects() != NULL);
386 live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
387 DCHECK(space->GetMarkObjects() != NULL);
388 mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
389 discontinuous_spaces_.push_back(space);
390}
391
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700392void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700393 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700394 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700395 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800396
397 // Dump cumulative loggers for each GC type.
398 // TODO: C++0x
399 uint64_t total_paused_time = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700400 typedef std::vector<collector::MarkSweep*>::const_iterator It;
401 for (It it = mark_sweep_collectors_.begin();
Sameer Abu Asala8439542013-02-14 16:06:42 -0800402 it != mark_sweep_collectors_.end(); ++it) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700403 collector::MarkSweep* collector = *it;
Sameer Abu Asala8439542013-02-14 16:06:42 -0800404 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800405 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700406 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800407 const uint64_t total_ns = logger.GetTotalNs();
Ian Rogers1d54e732013-05-02 21:10:01 -0700408 const uint64_t total_pause_ns = (*it)->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800409 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
410 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
411 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700412 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
413 << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
414 << collector->GetName() << " freed: " << freed_objects
415 << " objects with total size " << PrettySize(freed_bytes) << "\n"
416 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
417 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800418 total_duration += total_ns;
419 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700420 }
421 }
422 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Ian Rogers1d54e732013-05-02 21:10:01 -0700423 size_t total_objects_allocated = GetObjectsAllocatedEver();
424 size_t total_bytes_allocated = GetBytesAllocatedEver();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700425 if (total_duration != 0) {
426 const double total_seconds = double(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700427 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
428 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700429 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700430 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700431 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700432 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700433 os << "Total number of allocations: " << total_objects_allocated << "\n";
434 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700435 if (measure_allocation_time_) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700436 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
437 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
438 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700439 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700440 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
441 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700442}
443
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800444Heap::~Heap() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700445 if (kDumpGcPerformanceOnShutdown) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700446 DumpGcPerformanceInfo(LOG(INFO));
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700447 }
448
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800449 STLDeleteElements(&mark_sweep_collectors_);
450
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700451 // If we don't reset then the mark stack complains in it's destructor.
452 allocation_stack_->Reset();
453 live_stack_->Reset();
454
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800455 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800456 // We can't take the heap lock here because there might be a daemon thread suspended with the
457 // heap lock held. We know though that no non-daemon threads are executing, and we know that
458 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
459 // 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 -0700460 STLDeleteElements(&continuous_spaces_);
461 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 delete gc_complete_lock_;
Ian Rogers1d54e732013-05-02 21:10:01 -0700463 delete reference_queue_lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700464}
465
Ian Rogers1d54e732013-05-02 21:10:01 -0700466space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
467 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700468 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700469 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
470 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700471 if ((*it)->Contains(obj)) {
472 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700473 }
474 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700475 if (!fail_ok) {
476 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
477 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700478 return NULL;
479}
480
Ian Rogers1d54e732013-05-02 21:10:01 -0700481space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
482 bool fail_ok) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700483 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700484 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It;
485 for (It it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
486 if ((*it)->Contains(obj)) {
487 return *it;
488 }
489 }
490 if (!fail_ok) {
491 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
492 }
493 return NULL;
494}
495
496space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
497 space::Space* result = FindContinuousSpaceFromObject(obj, true);
498 if (result != NULL) {
499 return result;
500 }
501 return FindDiscontinuousSpaceFromObject(obj, true);
502}
503
504space::ImageSpace* Heap::GetImageSpace() const {
505 // TODO: C++0x auto
506 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
507 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700508 if ((*it)->IsImageSpace()) {
509 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700510 }
511 }
512 return NULL;
513}
514
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700515static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700516 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700517 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700518 size_t chunk_free_bytes = chunk_size - used_bytes;
519 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
520 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700521 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700522}
523
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800524mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
525 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700526 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
527 strlen(ClassHelper(c).GetDescriptor()) == 0);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800528 DCHECK_GE(byte_count, sizeof(mirror::Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700529
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800530 mirror::Object* obj = NULL;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700531 size_t size = 0;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700532 uint64_t allocation_start = 0;
533 if (measure_allocation_time_) {
534 allocation_start = NanoTime();
535 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700536
537 // We need to have a zygote space or else our newly allocated large object can end up in the
538 // Zygote resulting in it being prematurely freed.
539 // We can only do this for primive objects since large objects will not be within the card table
540 // range. This also means that we rely on SetClass not dirtying the object's card.
Ian Rogers22a20862013-03-16 16:34:57 -0700541 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700542 size = RoundUp(byte_count, kPageSize);
Ian Rogers1d54e732013-05-02 21:10:01 -0700543 obj = Allocate(self, large_object_space_, size);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700544 // Make sure that our large object didn't get placed anywhere within the space interval or else
545 // it breaks the immune range.
546 DCHECK(obj == NULL ||
Ian Rogers1d54e732013-05-02 21:10:01 -0700547 reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
548 reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700549 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700550 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700551
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700552 // Ensure that we did not allocate into a zygote space.
Ian Rogers1d54e732013-05-02 21:10:01 -0700553 DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700554 size = alloc_space_->AllocationSize(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700555 }
556
Mathieu Chartier037813d2012-08-23 16:44:59 -0700557 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700558 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700559
560 // Record allocation after since we want to use the atomic add for the atomic fence to guard
561 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700562 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700563
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700564 if (Dbg::IsAllocTrackingEnabled()) {
565 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700566 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700567 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700568 // We already have a request pending, no reason to start more until we update
569 // concurrent_start_bytes_.
570 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700571 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800572 SirtRef<mirror::Object> ref(self, obj);
Ian Rogers1f539342012-10-03 21:09:42 -0700573 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700574 }
575 VerifyObject(obj);
576
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700577 if (measure_allocation_time_) {
578 total_allocation_time_ += (NanoTime() - allocation_start) / kTimeAdjust;
579 }
580
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581 return obj;
582 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800583 std::ostringstream oss;
Mathieu Chartier037813d2012-08-23 16:44:59 -0700584 int64_t total_bytes_free = GetFreeMemory();
Ian Rogers1d54e732013-05-02 21:10:01 -0700585 uint64_t alloc_space_size = alloc_space_->GetBytesAllocated();
586 uint64_t large_object_size = large_object_space_->GetObjectsAllocated();
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800587 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
588 << " free bytes; allocation space size " << alloc_space_size
589 << "; large object space size " << large_object_size;
590 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
591 if (total_bytes_free >= byte_count) {
592 size_t max_contiguous_allocation = 0;
593 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700594 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
595 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
596 space::ContinuousSpace* space = *it;
597 if (space->IsDlMallocSpace()) {
598 space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800599 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700600 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800601 oss << "; failed due to fragmentation (largest possible contiguous allocation "
602 << max_contiguous_allocation << " bytes)";
Carl Shapiro58551df2011-07-24 03:09:51 -0700603 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800604 self->ThrowOutOfMemoryError(oss.str().c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700605 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700606}
607
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800608bool Heap::IsHeapAddress(const mirror::Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700609 // Note: we deliberately don't take the lock here, and mustn't test anything that would
610 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700611 if (obj == NULL) {
612 return true;
613 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700614 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700615 return false;
616 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700617 return FindSpaceFromObject(obj, true) != NULL;
Elliott Hughesa2501992011-08-26 19:39:54 -0700618}
619
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800620bool Heap::IsLiveObjectLocked(const mirror::Object* obj) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700621 //Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
622 if (obj == NULL) {
623 return false;
624 }
625 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
626 return false;
627 }
628 space::ContinuousSpace* cont_space = FindContinuousSpaceFromObject(obj, true);
629 if (cont_space != NULL) {
630 if (cont_space->GetLiveBitmap()->Test(obj)) {
631 return true;
632 }
633 } else {
634 space::DiscontinuousSpace* disc_space = FindDiscontinuousSpaceFromObject(obj, true);
635 if (disc_space != NULL) {
636 if (disc_space->GetLiveObjects()->Test(obj)) {
637 return true;
638 }
639 }
640 }
641 for (size_t i = 0; i < 5; ++i) {
642 if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj)) ||
643 live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
644 return true;
645 }
646 NanoSleep(MsToNs(10));
647 }
648 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700649}
650
Ian Rogers04d7aa92013-03-16 14:29:17 -0700651void Heap::VerifyObjectImpl(const mirror::Object* obj) {
652 if (Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700653 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700654 return;
655 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700656 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700657}
Elliott Hughes92b3b562011-09-08 16:32:26 -0700658
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700659void Heap::DumpSpaces() {
660 // TODO: C++0x auto
Ian Rogers1d54e732013-05-02 21:10:01 -0700661 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
662 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
663 space::ContinuousSpace* space = *it;
664 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
665 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700666 LOG(INFO) << space << " " << *space << "\n"
667 << live_bitmap << " " << *live_bitmap << "\n"
668 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700669 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700670 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
671 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
672 space::DiscontinuousSpace* space = *it;
673 LOG(INFO) << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700674 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700675}
676
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800677void Heap::VerifyObjectBody(const mirror::Object* obj) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800678 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700679 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700680 }
Ian Rogers62d6c772013-02-27 08:32:07 -0800681 if (UNLIKELY(GetObjectsAllocated() <= 10)) { // Ignore early dawn of the universe verifications.
682 return;
683 }
684 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
685 mirror::Object::ClassOffset().Int32Value();
686 const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
687 if (UNLIKELY(c == NULL)) {
688 LOG(FATAL) << "Null class in object: " << obj;
689 } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
690 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
691 }
692 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
693 // Note: we don't use the accessors here as they have internal sanity checks
694 // that we don't want to run
695 raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
696 const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
697 raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
698 const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
699 CHECK_EQ(c_c, c_c_c);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700700
Ian Rogers62d6c772013-02-27 08:32:07 -0800701 if (verify_object_mode_ != kVerifyAllFast) {
702 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
703 // heap_bitmap_lock_.
Ian Rogers1d54e732013-05-02 21:10:01 -0700704 if (!IsLiveObjectLocked(obj)) {
705 DumpSpaces();
706 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700707 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700708 if (!IsLiveObjectLocked(c)) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700709 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
710 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700711 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700712}
713
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800714void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700715 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700716 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700717}
718
719void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700720 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700721 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700722}
723
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800724void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700725 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700726 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700727 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700728
729 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700730 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700731 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700732 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700733
734 // TODO: Update these atomically.
735 RuntimeStats* global_stats = Runtime::Current()->GetStats();
736 ++global_stats->allocated_objects;
737 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700738 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700739
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700740 // This is safe to do since the GC will never free objects which are neither in the allocation
741 // stack or the live bitmap.
742 while (!allocation_stack_->AtomicPushBack(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700743 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700744 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700745}
746
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700747void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700748 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
749 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700750
751 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700752 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700753 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700754 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700755
756 // TODO: Do this concurrently.
757 RuntimeStats* global_stats = Runtime::Current()->GetStats();
758 global_stats->freed_objects += freed_objects;
759 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700760 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700761}
762
Ian Rogers1d54e732013-05-02 21:10:01 -0700763mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
764 bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700765 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800766 if (num_bytes_allocated_ + alloc_size > max_allowed_footprint_) {
767 // max_allowed_footprint_ <= growth_limit_ so it is safe to check in here.
768 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
769 // Completely out of memory.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700770 return NULL;
771 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700772 }
773
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700774 return space->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700775}
776
Ian Rogers1d54e732013-05-02 21:10:01 -0700777mirror::Object* Heap::Allocate(Thread* self, space::AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700778 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
779 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700780 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700781 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700782
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800783 mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700784 if (ptr != NULL) {
785 return ptr;
786 }
787
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700788 // The allocation failed. If the GC is running, block until it completes, and then retry the
789 // allocation.
Ian Rogers1d54e732013-05-02 21:10:01 -0700790 collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
791 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700792 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700793 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700794 if (ptr != NULL) {
795 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700796 }
797 }
798
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700799 // Loop through our different Gc types and try to Gc until we get enough free memory.
Ian Rogers1d54e732013-05-02 21:10:01 -0700800 for (size_t i = static_cast<size_t>(last_gc) + 1;
801 i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700802 bool run_gc = false;
Ian Rogers1d54e732013-05-02 21:10:01 -0700803 collector::GcType gc_type = static_cast<collector::GcType>(i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700804 switch (gc_type) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700805 case collector::kGcTypeSticky: {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700806 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700807 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
808 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700809 break;
810 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700811 case collector::kGcTypePartial:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700812 run_gc = have_zygote_space_;
813 break;
Ian Rogers1d54e732013-05-02 21:10:01 -0700814 case collector::kGcTypeFull:
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700815 run_gc = true;
816 break;
817 default:
818 break;
819 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700820
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700821 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700822 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Ian Rogers1d54e732013-05-02 21:10:01 -0700823 collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier65db8802012-11-20 12:36:46 -0800824 DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700825 i = static_cast<size_t>(gc_type_ran);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700826
827 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700828 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700829 if (ptr != NULL) {
830 return ptr;
831 }
832 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700833 }
834
835 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700836 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700837 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700838 if (ptr != NULL) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700839 return ptr;
840 }
841
Elliott Hughes81ff3182012-03-23 20:35:56 -0700842 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
843 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
844 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700845
Elliott Hughes418dfe72011-10-06 18:56:27 -0700846 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700847 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
848 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700849
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700850 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers1d54e732013-05-02 21:10:01 -0700851 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers50b35e22012-10-04 10:09:15 -0700852 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700853}
854
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700855void Heap::SetTargetHeapUtilization(float target) {
856 DCHECK_GT(target, 0.0f); // asserted in Java code
857 DCHECK_LT(target, 1.0f);
858 target_utilization_ = target;
859}
860
Ian Rogers1d54e732013-05-02 21:10:01 -0700861size_t Heap::GetObjectsAllocated() const {
862 size_t total = 0;
863 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
864 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
865 space::ContinuousSpace* space = *it;
866 if (space->IsDlMallocSpace()) {
867 total += space->AsDlMallocSpace()->GetObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700868 }
869 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700870 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
871 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
872 space::DiscontinuousSpace* space = *it;
873 total += space->AsLargeObjectSpace()->GetObjectsAllocated();
874 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700875 return total;
876}
877
Ian Rogers1d54e732013-05-02 21:10:01 -0700878size_t Heap::GetObjectsAllocatedEver() const {
879 size_t total = 0;
880 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
881 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
882 space::ContinuousSpace* space = *it;
883 if (space->IsDlMallocSpace()) {
884 total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700885 }
886 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700887 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
888 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
889 space::DiscontinuousSpace* space = *it;
890 total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
891 }
892 return total;
893}
894
895size_t Heap::GetBytesAllocatedEver() const {
896 size_t total = 0;
897 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
898 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
899 space::ContinuousSpace* space = *it;
900 if (space->IsDlMallocSpace()) {
901 total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
902 }
903 }
904 typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
905 for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
906 space::DiscontinuousSpace* space = *it;
907 total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
908 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700909 return total;
910}
911
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700912class InstanceCounter {
913 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800914 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700915 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800916 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700917 }
918
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800919 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800920 for (size_t i = 0; i < classes_.size(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800921 const mirror::Class* instance_class = o->GetClass();
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800922 if (use_is_assignable_from_) {
923 if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
924 ++counts_[i];
925 }
926 } else {
927 if (instance_class == classes_[i]) {
928 ++counts_[i];
929 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700930 }
931 }
932 }
933
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700934 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800935 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800936 bool use_is_assignable_from_;
937 uint64_t* const counts_;
938
939 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700940};
941
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800942void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -0800943 uint64_t* counts) {
944 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
945 // is empty, so the live bitmap is the only place we need to look.
946 Thread* self = Thread::Current();
947 self->TransitionFromRunnableToSuspended(kNative);
948 CollectGarbage(false);
949 self->TransitionFromSuspendedToRunnable();
950
951 InstanceCounter counter(classes, use_is_assignable_from, counts);
952 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700953 GetLiveBitmap()->Visit(counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700954}
955
Elliott Hughes3b78c942013-01-15 17:35:41 -0800956class InstanceCollector {
957 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800958 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -0800959 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
960 : class_(c), max_count_(max_count), instances_(instances) {
961 }
962
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800963 void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
964 const mirror::Class* instance_class = o->GetClass();
Elliott Hughes3b78c942013-01-15 17:35:41 -0800965 if (instance_class == class_) {
966 if (max_count_ == 0 || instances_.size() < max_count_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800967 instances_.push_back(const_cast<mirror::Object*>(o));
Elliott Hughes3b78c942013-01-15 17:35:41 -0800968 }
969 }
970 }
971
972 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800973 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800974 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800975 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -0800976
977 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
978};
979
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800980void Heap::GetInstances(mirror::Class* c, int32_t max_count,
981 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -0800982 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
983 // is empty, so the live bitmap is the only place we need to look.
984 Thread* self = Thread::Current();
985 self->TransitionFromRunnableToSuspended(kNative);
986 CollectGarbage(false);
987 self->TransitionFromSuspendedToRunnable();
988
989 InstanceCollector collector(c, max_count, instances);
990 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
991 GetLiveBitmap()->Visit(collector);
992}
993
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800994class ReferringObjectsFinder {
995 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800996 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
997 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -0800998 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
999 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1000 }
1001
1002 // For bitmap Visit.
1003 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1004 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001005 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001006 collector::MarkSweep::VisitObjectReferences(o, *this);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001007 }
1008
1009 // For MarkSweep::VisitObjectReferences.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001010 void operator ()(const mirror::Object* referrer, const mirror::Object* object,
1011 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001012 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001013 referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001014 }
1015 }
1016
1017 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001018 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001019 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001020 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001021
1022 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1023};
1024
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001025void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1026 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001027 // We only want reachable instances, so do a GC. This also ensures that the alloc stack
1028 // is empty, so the live bitmap is the only place we need to look.
1029 Thread* self = Thread::Current();
1030 self->TransitionFromRunnableToSuspended(kNative);
1031 CollectGarbage(false);
1032 self->TransitionFromSuspendedToRunnable();
1033
1034 ReferringObjectsFinder finder(o, max_count, referring_objects);
1035 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1036 GetLiveBitmap()->Visit(finder);
1037}
1038
Ian Rogers30fab402012-01-23 15:43:46 -08001039void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001040 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1041 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -07001042 Thread* self = Thread::Current();
1043 WaitForConcurrentGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001044 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001045}
1046
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001047void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001048 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001049 // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
1050 CollectGarbage(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001051 Thread* self = Thread::Current();
1052 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001053
1054 // Try to see if we have any Zygote spaces.
1055 if (have_zygote_space_) {
1056 return;
1057 }
1058
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001059 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
1060
1061 {
1062 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -07001063 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001064 FlushAllocStack();
1065 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001066
Ian Rogers1d54e732013-05-02 21:10:01 -07001067 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
1068 // of the remaining available heap memory.
1069 space::DlMallocSpace* zygote_space = alloc_space_;
1070 alloc_space_ = zygote_space->CreateZygoteSpace();
1071 alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001072
Ian Rogers1d54e732013-05-02 21:10:01 -07001073 // Change the GC retention policy of the zygote space to only collect when full.
1074 zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
1075 AddContinuousSpace(alloc_space_);
1076 have_zygote_space_ = true;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001077
Ian Rogers5f5a2c02012-09-17 10:52:08 -07001078 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001079 // TODO: C++0x
Ian Rogers1d54e732013-05-02 21:10:01 -07001080 typedef std::vector<collector::MarkSweep*>::const_iterator It;
1081 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1082 it != end; ++it) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001083 (*it)->ResetCumulativeStatistics();
Mathieu Chartier0325e622012-09-05 14:22:51 -07001084 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001085}
1086
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001087void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001088 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1089 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001090 allocation_stack_->Reset();
1091}
1092
Ian Rogers1d54e732013-05-02 21:10:01 -07001093void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1094 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001095 mirror::Object** limit = stack->End();
1096 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1097 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001098 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001099 if (LIKELY(bitmap->HasAddress(obj))) {
1100 bitmap->Set(obj);
1101 } else {
1102 large_objects->Set(obj);
1103 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001104 }
1105}
1106
Ian Rogers1d54e732013-05-02 21:10:01 -07001107void Heap::UnMarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
1108 accounting::ObjectStack* stack) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001109 mirror::Object** limit = stack->End();
1110 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1111 const mirror::Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001112 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001113 if (LIKELY(bitmap->HasAddress(obj))) {
1114 bitmap->Clear(obj);
1115 } else {
1116 large_objects->Clear(obj);
1117 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001118 }
1119}
1120
Ian Rogers1d54e732013-05-02 21:10:01 -07001121collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1122 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001123 Thread* self = Thread::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001124 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001125 Locks::mutator_lock_->AssertNotHeld(self);
Carl Shapiro58551df2011-07-24 03:09:51 -07001126
Ian Rogers120f1c72012-09-28 17:17:10 -07001127 if (self->IsHandlingStackOverflow()) {
1128 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1129 }
1130
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001131 // Ensure there is only one GC at a time.
1132 bool start_collect = false;
1133 while (!start_collect) {
1134 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001135 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001136 if (!is_gc_running_) {
1137 is_gc_running_ = true;
1138 start_collect = true;
1139 }
1140 }
1141 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001142 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001143 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
1144 // Not doing at the moment to ensure soft references are cleared.
1145 }
1146 }
Ian Rogers81d425b2012-09-27 16:03:43 -07001147 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001148
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001149 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
1150 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
1151 ++Thread::Current()->GetStats()->gc_for_alloc_count;
1152 }
1153
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001154 // We need to do partial GCs every now and then to avoid the heap growing too much and
1155 // fragmenting.
Ian Rogers1d54e732013-05-02 21:10:01 -07001156 // TODO: if sticky GCs are failing to free memory then we should lower the
1157 // sticky_to_partial_gc_ratio_, if they are successful we can increase it.
1158 if (gc_type == collector::kGcTypeSticky) {
1159 ++sticky_gc_count_;
1160 if (sticky_gc_count_ >= sticky_to_partial_gc_ratio_) {
1161 gc_type = have_zygote_space_ ? collector::kGcTypePartial : collector::kGcTypeFull;
1162 sticky_gc_count_ = 0;
1163 }
1164 } else {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001165 sticky_gc_count_ = 0;
1166 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001167
Ian Rogers1d54e732013-05-02 21:10:01 -07001168 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001169 uint64_t gc_start_size = GetBytesAllocated();
1170 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001171 if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
Jeff Hao9bd02812013-02-08 14:29:50 -08001172 LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
1173 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001174 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001175 if (ms_delta != 0) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001176 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001177 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1178 }
1179
Ian Rogers1d54e732013-05-02 21:10:01 -07001180 DCHECK_LT(gc_type, collector::kGcTypeMax);
1181 DCHECK_NE(gc_type, collector::kGcTypeNone);
1182 collector::MarkSweep* collector = NULL;
1183 typedef std::vector<collector::MarkSweep*>::iterator It;
1184 for (It it = mark_sweep_collectors_.begin(), end = mark_sweep_collectors_.end();
1185 it != end; ++it) {
1186 collector::MarkSweep* cur_collector = *it;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001187 if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
1188 collector = cur_collector;
1189 break;
1190 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001191 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001192 CHECK(collector != NULL)
1193 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1194 << " and type=" << gc_type;
1195 collector->clear_soft_references_ = clear_soft_references;
1196 collector->Run();
Ian Rogers1d54e732013-05-02 21:10:01 -07001197 total_objects_freed_ever_ += collector->GetFreedObjects();
1198 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001199
Ian Rogers1d54e732013-05-02 21:10:01 -07001200 const size_t duration = collector->GetDurationNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001201 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1202 bool was_slow = duration > kSlowGcThreshold ||
1203 (gc_cause == kGcCauseForAlloc && duration > kLongGcPauseThreshold);
1204 for (size_t i = 0; i < pauses.size(); ++i) {
1205 if (pauses[i] > kLongGcPauseThreshold) {
1206 was_slow = true;
1207 }
1208 }
1209
1210 if (was_slow) {
1211 const size_t percent_free = GetPercentFree();
Ian Rogers1d54e732013-05-02 21:10:01 -07001212 const size_t current_heap_size = GetBytesAllocated();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001213 const size_t total_memory = GetTotalMemory();
1214 std::ostringstream pause_string;
1215 for (size_t i = 0; i < pauses.size(); ++i) {
1216 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1217 << ((i != pauses.size() - 1) ? ", " : "");
1218 }
1219 LOG(INFO) << gc_cause << " " << collector->GetName()
Sameer Abu Asala8439542013-02-14 16:06:42 -08001220 << "GC freed " << PrettySize(collector->GetFreedBytes()) << ", "
1221 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1222 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1223 << " total " << PrettyDuration((duration / 1000) * 1000);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001224 if (VLOG_IS_ON(heap)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001225 LOG(INFO) << Dumpable<base::NewTimingLogger>(collector->GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001226 }
1227 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001228
Ian Rogers15bf2d32012-08-28 17:33:04 -07001229 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001230 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001231 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001232 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -07001233 // Wake anyone who may have been waiting for the GC to complete.
Ian Rogersc604d732012-10-14 16:09:54 -07001234 gc_complete_cond_->Broadcast(self);
Ian Rogers15bf2d32012-08-28 17:33:04 -07001235 }
1236 // Inform DDMS that a GC completed.
1237 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001238 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001239}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001240
Ian Rogers1d54e732013-05-02 21:10:01 -07001241void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::NewTimingLogger& timings,
1242 collector::GcType gc_type) {
1243 if (gc_type == collector::kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001244 // 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 -07001245 // cards.
1246 return;
1247 }
1248
1249 // Update zygote mod union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001250 if (gc_type == collector::kGcTypePartial) {
1251 timings.NewSplit("UpdateZygoteModUnionTable");
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001252 zygote_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001253
Ian Rogers1d54e732013-05-02 21:10:01 -07001254 timings.NewSplit("ZygoteMarkReferences");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001255 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001256 }
1257
1258 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001259 timings.NewSplit("UpdateModUnionTable");
1260 image_mod_union_table_->Update();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001261
1262 // Scans all objects in the mod-union table.
Ian Rogers1d54e732013-05-02 21:10:01 -07001263 timings.NewSplit("MarkImageToAllocSpaceReferences");
1264 image_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001265}
1266
Ian Rogers1d54e732013-05-02 21:10:01 -07001267static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001268 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001269 if (root == obj) {
1270 LOG(INFO) << "Object " << obj << " is a root";
1271 }
1272}
1273
1274class ScanVisitor {
1275 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001276 void operator ()(const mirror::Object* obj) const {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001277 LOG(INFO) << "Would have rescanned object " << obj;
1278 }
1279};
1280
Ian Rogers1d54e732013-05-02 21:10:01 -07001281// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001282class VerifyReferenceVisitor {
1283 public:
Ian Rogers1d54e732013-05-02 21:10:01 -07001284 VerifyReferenceVisitor(Heap* heap)
1285 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
1286 : heap_(heap), failed_(false) {
1287 }
1288
1289 bool Failed() const {
1290 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001291 }
1292
1293 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001294 // analysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001295 void operator ()(const mirror::Object* obj, const mirror::Object* ref,
Ian Rogers1d54e732013-05-02 21:10:01 -07001296 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001297 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001298 // Verify that the reference is live.
Ian Rogers1d54e732013-05-02 21:10:01 -07001299 if (UNLIKELY(ref != NULL && !IsLive(ref))) {
1300 accounting::CardTable* card_table = heap_->GetCardTable();
1301 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1302 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001303
Ian Rogers1d54e732013-05-02 21:10:01 -07001304 if (obj != NULL) {
1305 byte* card_addr = card_table->CardFromAddr(obj);
1306 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset " << offset
1307 << "\nIsDirty = " << (*card_addr == accounting::CardTable::kCardDirty)
1308 << "\nObj type " << PrettyTypeOf(obj)
1309 << "\nRef type " << PrettyTypeOf(ref);
1310 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1311 void* cover_begin = card_table->AddrFromCard(card_addr);
1312 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1313 accounting::CardTable::kCardSize);
1314 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1315 << "-" << cover_end;
1316 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001317
Ian Rogers1d54e732013-05-02 21:10:01 -07001318 // Print out how the object is live.
1319 if (bitmap != NULL && bitmap->Test(obj)) {
1320 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1321 }
1322 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
1323 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1324 }
1325 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
1326 LOG(ERROR) << "Object " << obj << " found in live stack";
1327 }
1328 // Attempt to see if the card table missed the reference.
1329 ScanVisitor scan_visitor;
1330 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1331 card_table->Scan(bitmap, byte_cover_begin,
1332 byte_cover_begin + accounting::CardTable::kCardSize,
1333 scan_visitor, VoidFunctor());
1334
1335 // Search to see if any of the roots reference our object.
1336 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1337 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1338
1339 // Search to see if any of the roots reference our reference.
1340 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
1341 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
1342 } else {
1343 LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001344 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001345 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1346 LOG(ERROR) << "Reference " << ref << " found in allocation stack!";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001347 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001348 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001349 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001350 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001351 heap_->image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
1352 heap_->zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
1353 failed_ = true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001354 }
1355 }
1356
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001357 bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers1d54e732013-05-02 21:10:01 -07001358 return heap_->IsLiveObjectLocked(obj);
1359 }
1360
1361 static void VerifyRoots(const mirror::Object* root, void* arg) {
1362 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
1363 (*visitor)(NULL, root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001364 }
1365
1366 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001367 Heap* const heap_;
1368 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001369};
1370
Ian Rogers1d54e732013-05-02 21:10:01 -07001371// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001372class VerifyObjectVisitor {
1373 public:
Ian Rogers1d54e732013-05-02 21:10:01 -07001374 VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001375 }
1376
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001377 void operator ()(const mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001378 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001379 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1380 // be live or else how did we find it in the live bitmap?
1381 VerifyReferenceVisitor visitor(heap_);
1382 collector::MarkSweep::VisitObjectReferences(obj, visitor);
1383 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001384 }
1385
1386 bool Failed() const {
1387 return failed_;
1388 }
1389
1390 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001391 Heap* const heap_;
1392 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001393};
1394
1395// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001396bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001397 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001398 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07001399 allocation_stack_->Sort();
1400 live_stack_->Sort();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001401 // Perform the verification.
1402 VerifyObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -07001403 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001404 GetLiveBitmap()->Visit(visitor);
1405 // We don't want to verify the objects in the allocation stack since they themselves may be
1406 // pointing to dead objects if they are not reachable.
1407 if (visitor.Failed()) {
1408 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001409 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001410 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001411 return true;
1412}
1413
1414class VerifyReferenceCardVisitor {
1415 public:
1416 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1417 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1418 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07001419 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001420 }
1421
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001422 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1423 // annotalysis on visitors.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001424 void operator ()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
1425 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001426 // Filter out class references since changing an object's class does not mark the card as dirty.
1427 // Also handles large objects, since the only reference they hold is a class reference.
1428 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001429 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001430 // If the object is not dirty and it is referencing something in the live stack other than
1431 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001432 if (!card_table->AddrIsInCardTable(obj)) {
1433 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1434 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001435 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001436 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
1437 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001438 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
1439 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1440 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001441 LOG(ERROR) << "Object " << obj << " found in live stack";
1442 }
1443 if (heap_->GetLiveBitmap()->Test(obj)) {
1444 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1445 }
1446 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1447 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1448
1449 // Print which field of the object is dead.
1450 if (!obj->IsObjectArray()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001451 const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001452 CHECK(klass != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001453 const mirror::ObjectArray<mirror::Field>* fields = is_static ? klass->GetSFields()
1454 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001455 CHECK(fields != NULL);
1456 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001457 const mirror::Field* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001458 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1459 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1460 << PrettyField(cur);
1461 break;
1462 }
1463 }
1464 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001465 const mirror::ObjectArray<mirror::Object>* object_array =
1466 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001467 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1468 if (object_array->Get(i) == ref) {
1469 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1470 }
1471 }
1472 }
1473
1474 *failed_ = true;
1475 }
1476 }
1477 }
1478 }
1479
1480 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001481 Heap* const heap_;
1482 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001483};
1484
1485class VerifyLiveStackReferences {
1486 public:
1487 VerifyLiveStackReferences(Heap* heap)
1488 : heap_(heap),
1489 failed_(false) {
1490
1491 }
1492
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001493 void operator ()(const mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001494 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1495 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogers1d54e732013-05-02 21:10:01 -07001496 collector::MarkSweep::VisitObjectReferences(obj, visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001497 }
1498
1499 bool Failed() const {
1500 return failed_;
1501 }
1502
1503 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001504 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001505 bool failed_;
1506};
1507
1508bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001509 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001510
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001511 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07001512 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001513 VerifyLiveStackReferences visitor(this);
1514 GetLiveBitmap()->Visit(visitor);
1515
1516 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001517 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001518 visitor(*it);
1519 }
1520
1521 if (visitor.Failed()) {
1522 DumpSpaces();
1523 return false;
1524 }
1525 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001526}
1527
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001528void Heap::SwapStacks() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001529 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001530
1531 // Sort the live stack so that we can quickly binary search it later.
Ian Rogers04d7aa92013-03-16 14:29:17 -07001532 if (verify_object_mode_ > kNoHeapVerification) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001533 live_stack_->Sort();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001534 }
1535}
1536
Ian Rogers1d54e732013-05-02 21:10:01 -07001537void Heap::ProcessCards(base::NewTimingLogger& timings) {
1538 // Clear cards and keep track of cards cleared in the mod-union table.
1539 typedef std::vector<space::ContinuousSpace*>::iterator It;
1540 for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
1541 space::ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001542 if (space->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001543 timings.NewSplit("ModUnionClearCards");
1544 image_mod_union_table_->ClearCards(space);
1545 } else if (space->IsZygoteSpace()) {
1546 timings.NewSplit("ZygoteModUnionClearCards");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001547 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001548 } else {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001549 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
1550 // were dirty before the GC started.
Ian Rogers1d54e732013-05-02 21:10:01 -07001551 timings.NewSplit("AllocSpaceClearCards");
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001552 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001553 }
1554 }
1555}
1556
Ian Rogers1d54e732013-05-02 21:10:01 -07001557void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001558 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1559 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001560
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001561 if (verify_pre_gc_heap_) {
1562 thread_list->SuspendAll();
1563 {
1564 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1565 if (!VerifyHeapReferences()) {
1566 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
1567 }
1568 }
1569 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001570 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001571
1572 // Check that all objects which reference things in the live stack are on dirty cards.
1573 if (verify_missing_card_marks_) {
1574 thread_list->SuspendAll();
1575 {
1576 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1577 SwapStacks();
1578 // Sort the live stack so that we can quickly binary search it later.
1579 if (!VerifyMissingCardMarks()) {
1580 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
1581 }
1582 SwapStacks();
1583 }
1584 thread_list->ResumeAll();
1585 }
1586
1587 if (verify_mod_union_table_) {
1588 thread_list->SuspendAll();
1589 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
1590 zygote_mod_union_table_->Update();
1591 zygote_mod_union_table_->Verify();
Ian Rogers1d54e732013-05-02 21:10:01 -07001592 image_mod_union_table_->Update();
1593 image_mod_union_table_->Verify();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001594 thread_list->ResumeAll();
1595 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08001596}
1597
Ian Rogers1d54e732013-05-02 21:10:01 -07001598void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001599 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001600
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001601 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
1602 // reachable objects.
1603 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001604 Thread* self = Thread::Current();
1605 CHECK_NE(self->GetState(), kRunnable);
1606 Locks::mutator_lock_->SharedUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001607 thread_list->SuspendAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001608 {
1609 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1610 // Swapping bound bitmaps does nothing.
1611 gc->SwapBitmaps();
1612 if (!VerifyHeapReferences()) {
1613 LOG(FATAL) << "Post " << gc->GetName() << "GC verification failed";
1614 }
1615 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001616 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001617 thread_list->ResumeAll();
Ian Rogers1d54e732013-05-02 21:10:01 -07001618 Locks::mutator_lock_->SharedLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001619 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001620}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001621
Ian Rogers1d54e732013-05-02 21:10:01 -07001622void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001623 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001624
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001625 if (verify_system_weaks_) {
1626 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001627 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001628 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001629 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001630}
1631
Ian Rogers1d54e732013-05-02 21:10:01 -07001632collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
1633 collector::GcType last_gc_type = collector::kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001634 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001635 bool do_wait;
1636 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001637 {
1638 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001639 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001640 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001641 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001642 if (do_wait) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001643 uint64_t wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001644 // We must wait, change thread state then sleep on gc_complete_cond_;
1645 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1646 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001647 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001648 while (is_gc_running_) {
Ian Rogersc604d732012-10-14 16:09:54 -07001649 gc_complete_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001650 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001651 last_gc_type = last_gc_type_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001652 wait_time = NanoTime() - wait_start;;
1653 total_wait_time_ += wait_time;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001654 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001655 if (wait_time > kLongGcPauseThreshold) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001656 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1657 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001658 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001659 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001660 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001661}
1662
Elliott Hughesc967f782012-04-16 10:23:15 -07001663void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001664 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001665 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001666 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07001667}
1668
1669size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001670 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001671}
1672
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001673void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001674 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001675 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001676 << PrettySize(GetMaxMemory());
1677 max_allowed_footprint = GetMaxMemory();
1678 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001679 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001680}
1681
Mathieu Chartier65db8802012-11-20 12:36:46 -08001682void Heap::GrowForUtilization(uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001683 // We know what our utilization is at this moment.
1684 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08001685 const size_t bytes_allocated = GetBytesAllocated();
1686 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07001687 last_gc_time_ns_ = NanoTime();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001688
Mathieu Chartier65db8802012-11-20 12:36:46 -08001689 size_t target_size = bytes_allocated / GetTargetHeapUtilization();
1690 if (target_size > bytes_allocated + max_free_) {
1691 target_size = bytes_allocated + max_free_;
1692 } else if (target_size < bytes_allocated + min_free_) {
1693 target_size = bytes_allocated + min_free_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001694 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001695
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001696 SetIdealFootprint(target_size);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001697
Ian Rogers1d54e732013-05-02 21:10:01 -07001698 // Calculate when to perform the next ConcurrentGC.
1699 if (concurrent_gc_) {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001700 // Calculate the estimated GC duration.
1701 double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
1702 // Estimate how many remaining bytes we will have when we need to start the next GC.
1703 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Ian Rogers1d54e732013-05-02 21:10:01 -07001704 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
1705 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
1706 // A never going to happen situation that from the estimated allocation rate we will exceed
1707 // the applications entire footprint with the given estimated allocation rate. Schedule
1708 // another GC straight away.
1709 concurrent_start_bytes_ = bytes_allocated;
1710 } else {
Mathieu Chartier65db8802012-11-20 12:36:46 -08001711 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
1712 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
1713 // right away.
1714 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001715 }
1716 DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
1717 DCHECK_LE(max_allowed_footprint_, growth_limit_);
1718 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001719}
1720
jeffhaoc1160702011-10-27 15:48:45 -07001721void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08001722 growth_limit_ = capacity_;
jeffhaoc1160702011-10-27 15:48:45 -07001723 alloc_space_->ClearGrowthLimit();
1724}
1725
Elliott Hughesadb460d2011-10-05 17:02:34 -07001726void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001727 MemberOffset reference_queue_offset,
1728 MemberOffset reference_queueNext_offset,
1729 MemberOffset reference_pendingNext_offset,
1730 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001731 reference_referent_offset_ = reference_referent_offset;
1732 reference_queue_offset_ = reference_queue_offset;
1733 reference_queueNext_offset_ = reference_queueNext_offset;
1734 reference_pendingNext_offset_ = reference_pendingNext_offset;
1735 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1736 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1737 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1738 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1739 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1740 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1741}
1742
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001743mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001744 DCHECK(reference != NULL);
1745 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001746 return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001747}
1748
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001749void Heap::ClearReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001750 DCHECK(reference != NULL);
1751 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1752 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1753}
1754
1755// Returns true if the reference object has not yet been enqueued.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001756bool Heap::IsEnqueuable(const mirror::Object* ref) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001757 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001758 const mirror::Object* queue =
1759 ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
1760 const mirror::Object* queue_next =
1761 ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001762 return (queue != NULL) && (queue_next == NULL);
1763}
1764
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001765void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001766 DCHECK(ref != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001767 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
1768 CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001769 EnqueuePendingReference(ref, cleared_reference_list);
1770}
1771
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001772void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001773 DCHECK(ref != NULL);
1774 DCHECK(list != NULL);
1775
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001776 // TODO: Remove this lock, use atomic stacks for storing references.
1777 MutexLock mu(Thread::Current(), *reference_queue_lock_);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001778 if (*list == NULL) {
1779 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1780 *list = ref;
1781 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001782 mirror::Object* head =
1783 (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001784 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1785 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1786 }
1787}
1788
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001789mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001790 DCHECK(list != NULL);
1791 DCHECK(*list != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001792 mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1793 false);
1794 mirror::Object* ref;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001795
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001796 // Note: the following code is thread-safe because it is only called from ProcessReferences which
1797 // is single threaded.
Elliott Hughesadb460d2011-10-05 17:02:34 -07001798 if (*list == head) {
1799 ref = *list;
1800 *list = NULL;
1801 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001802 mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
1803 false);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001804 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1805 ref = head;
1806 }
1807 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1808 return ref;
1809}
1810
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001811void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001812 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08001813 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001814 ArgArray arg_array(NULL, 0);
1815 arg_array.Append(reinterpret_cast<uint32_t>(object));
1816 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Jeff Hao6474d192013-03-26 14:08:09 -07001817 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001818}
1819
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001820void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001821 DCHECK(cleared != NULL);
1822 if (*cleared != NULL) {
Ian Rogers64b6d142012-10-29 16:34:15 -07001823 // When a runtime isn't started there are no reference queues to care about so ignore.
1824 if (LIKELY(Runtime::Current()->IsStarted())) {
1825 ScopedObjectAccess soa(Thread::Current());
Jeff Hao5d917302013-02-27 17:57:33 -08001826 JValue result;
Jeff Hao5d917302013-02-27 17:57:33 -08001827 ArgArray arg_array(NULL, 0);
1828 arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
1829 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Jeff Hao6474d192013-03-26 14:08:09 -07001830 arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
Ian Rogers64b6d142012-10-29 16:34:15 -07001831 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001832 *cleared = NULL;
1833 }
1834}
1835
Ian Rogers1f539342012-10-03 21:09:42 -07001836void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001837 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001838 Runtime* runtime = Runtime::Current();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001839 DCHECK(concurrent_gc_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001840 if (runtime == NULL || !runtime->IsFinishedStarting() ||
Ian Rogers120f1c72012-09-28 17:17:10 -07001841 !runtime->IsConcurrentGcEnabled()) {
1842 return;
1843 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001844 {
1845 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1846 if (runtime->IsShuttingDown()) {
1847 return;
1848 }
1849 }
1850 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001851 return;
1852 }
1853
Ian Rogers120f1c72012-09-28 17:17:10 -07001854 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001855 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1856 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001857 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1858 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001859 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001860}
1861
Ian Rogers81d425b2012-09-27 16:03:43 -07001862void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001863 {
1864 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier65db8802012-11-20 12:36:46 -08001865 if (Runtime::Current()->IsShuttingDown()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001866 return;
1867 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001868 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001869
Mathieu Chartier65db8802012-11-20 12:36:46 -08001870 // Wait for any GCs currently running to finish.
Ian Rogers1d54e732013-05-02 21:10:01 -07001871 if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001872 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001873 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001874 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07001875 CollectGarbageInternal(collector::kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001876 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001877 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001878}
1879
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001880void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08001881 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
1882 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
1883 // a space it will hold its lock and can become a cause of jank.
1884 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
1885 // forking.
1886
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001887 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1888 // because that only marks object heads, so a large array looks like lots of empty space. We
1889 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1890 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1891 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1892 // not how much use we're making of those pages.
Ian Rogers48931882013-01-22 14:35:16 -08001893 uint64_t ms_time = MilliTime();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001894 float utilization =
Ian Rogers1d54e732013-05-02 21:10:01 -07001895 static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
1896 if ((utilization > 0.75f) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001897 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1898 // heap trim occurred in the last two seconds.
1899 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001900 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001901
1902 Thread* self = Thread::Current();
1903 {
1904 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1905 Runtime* runtime = Runtime::Current();
1906 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1907 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1908 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1909 // as we don't hold the lock while requesting the trim).
1910 return;
1911 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001912 }
Ian Rogers48931882013-01-22 14:35:16 -08001913
1914 SchedPolicy policy;
1915 get_sched_policy(self->GetTid(), &policy);
1916 if (policy == SP_FOREGROUND || policy == SP_AUDIO_APP) {
1917 // Don't trim the heap if we are a foreground or audio app.
1918 return;
1919 }
1920
Ian Rogers1d54e732013-05-02 21:10:01 -07001921 last_trim_time_ms_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001922 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001923 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1924 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001925 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1926 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001927 CHECK(!env->ExceptionCheck());
1928}
1929
Ian Rogers48931882013-01-22 14:35:16 -08001930size_t Heap::Trim() {
1931 // Handle a requested heap trim on a thread outside of the main GC thread.
1932 return alloc_space_->Trim();
1933}
1934
Ian Rogers1d54e732013-05-02 21:10:01 -07001935} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001936} // namespace art