blob: e50a31cf0b4498862b801834cb45be6bc29c2ddf [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
Ian Rogers5d76c432011-10-31 21:42:49 -070025#include "card_table.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070026#include "debugger.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070027#include "image.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070028#include "mark_sweep.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070029#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080031#include "os.h"
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080032#include "scoped_heap_lock.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070033#include "space.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070034#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070035#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070036#include "timing_logger.h"
37#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070038#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070039
40namespace art {
41
Ian Rogers30fab402012-01-23 15:43:46 -080042static void UpdateFirstAndLastSpace(Space** first_space, Space** last_space, Space* space) {
43 if (*first_space == NULL) {
44 *first_space = space;
45 *last_space = space;
46 } else {
47 if ((*first_space)->Begin() > space->Begin()) {
48 *first_space = space;
49 } else if (space->Begin() > (*last_space)->Begin()) {
50 *last_space = space;
51 }
52 }
53}
54
Elliott Hughesae80b492012-04-24 10:43:17 -070055static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080056 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080057 std::vector<std::string> boot_class_path;
58 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070059 if (boot_class_path.empty()) {
60 LOG(FATAL) << "Failed to generate image because no boot class path specified";
61 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080062
63 std::vector<char*> arg_vector;
64
65 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070066 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080067 const char* dex2oat = dex2oat_string.c_str();
68 arg_vector.push_back(strdup(dex2oat));
69
70 std::string image_option_string("--image=");
71 image_option_string += image_file_name;
72 const char* image_option = image_option_string.c_str();
73 arg_vector.push_back(strdup(image_option));
74
75 arg_vector.push_back(strdup("--runtime-arg"));
76 arg_vector.push_back(strdup("-Xms64m"));
77
78 arg_vector.push_back(strdup("--runtime-arg"));
79 arg_vector.push_back(strdup("-Xmx64m"));
80
81 for (size_t i = 0; i < boot_class_path.size(); i++) {
82 std::string dex_file_option_string("--dex-file=");
83 dex_file_option_string += boot_class_path[i];
84 const char* dex_file_option = dex_file_option_string.c_str();
85 arg_vector.push_back(strdup(dex_file_option));
86 }
87
88 std::string oat_file_option_string("--oat-file=");
89 oat_file_option_string += image_file_name;
90 oat_file_option_string.erase(oat_file_option_string.size() - 3);
91 oat_file_option_string += "oat";
92 const char* oat_file_option = oat_file_option_string.c_str();
93 arg_vector.push_back(strdup(oat_file_option));
94
95 arg_vector.push_back(strdup("--base=0x60000000"));
96
Elliott Hughes48436bb2012-02-07 15:23:28 -080097 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080098 LOG(INFO) << command_line;
99
Elliott Hughes48436bb2012-02-07 15:23:28 -0800100 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800101 char** argv = &arg_vector[0];
102
103 // fork and exec dex2oat
104 pid_t pid = fork();
105 if (pid == 0) {
106 // no allocation allowed between fork and exec
107
108 // change process groups, so we don't get reaped by ProcessManager
109 setpgid(0, 0);
110
111 execv(dex2oat, argv);
112
113 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
114 return false;
115 } else {
116 STLDeleteElements(&arg_vector);
117
118 // wait for dex2oat to finish
119 int status;
120 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
121 if (got_pid != pid) {
122 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
123 return false;
124 }
125 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
126 LOG(ERROR) << dex2oat << " failed: " << command_line;
127 return false;
128 }
129 }
130 return true;
131}
132
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800133Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
134 const std::string& original_image_file_name)
135 : lock_(NULL),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700136 image_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800137 alloc_space_(NULL),
138 mark_bitmap_(NULL),
139 live_bitmap_(NULL),
140 card_table_(NULL),
141 card_marking_disabled_(false),
142 is_gc_running_(false),
143 num_bytes_allocated_(0),
144 num_objects_allocated_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800145 reference_referent_offset_(0),
146 reference_queue_offset_(0),
147 reference_queueNext_offset_(0),
148 reference_pendingNext_offset_(0),
149 finalizer_reference_zombie_offset_(0),
150 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700151 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800152 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800153 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700154 }
155
Ian Rogers30fab402012-01-23 15:43:46 -0800156 // Compute the bounds of all spaces for allocating live and mark bitmaps
157 // there will be at least one space (the alloc space)
158 Space* first_space = NULL;
159 Space* last_space = NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700160
Ian Rogers30fab402012-01-23 15:43:46 -0800161 // Requested begin for the alloc space, to follow the mapped image and oat files
162 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800163 std::string image_file_name(original_image_file_name);
164 if (!image_file_name.empty()) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800165 if (OS::FileExists(image_file_name.c_str())) {
166 // If the /system file exists, it should be up-to-date, don't try to generate
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700167 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800168 } else {
169 // If the /system file didn't exist, we need to use one from the art-cache.
170 // If the cache file exists, try to open, but if it fails, regenerate.
171 // If it does not exist, generate.
172 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
173 if (OS::FileExists(image_file_name.c_str())) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700174 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800175 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700176 if (image_space_ == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800177 if (!GenerateImage(image_file_name)) {
178 LOG(FATAL) << "Failed to generate image: " << image_file_name;
179 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700180 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800181 }
182 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700183 if (image_space_ == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800184 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700185 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800186
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700187 AddSpace(image_space_);
188 UpdateFirstAndLastSpace(&first_space, &last_space, image_space_);
Ian Rogers30fab402012-01-23 15:43:46 -0800189 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
190 // isn't going to get in the middle
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700191 byte* oat_end_addr = image_space_->GetImageHeader().GetOatEnd();
192 CHECK(oat_end_addr > image_space_->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800193 if (oat_end_addr > requested_begin) {
194 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
195 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700196 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700197 }
198
Ian Rogers30fab402012-01-23 15:43:46 -0800199 alloc_space_ = Space::CreateAllocSpace("alloc space", initial_size, growth_limit, capacity,
200 requested_begin);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700201 if (alloc_space_ == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700202 LOG(FATAL) << "Failed to create alloc space";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700203 }
Ian Rogers30fab402012-01-23 15:43:46 -0800204 AddSpace(alloc_space_);
205 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
206 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800207 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700208
209 // Allocate the initial live bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800210 UniquePtr<HeapBitmap> live_bitmap(HeapBitmap::Create("dalvik-bitmap-1", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700211 if (live_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700212 LOG(FATAL) << "Failed to create live bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700213 }
214
Ian Rogers30fab402012-01-23 15:43:46 -0800215 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800216 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800217 Space* space = spaces_[i];
218 if (space->IsImageSpace()) {
219 space->AsImageSpace()->RecordImageAllocations(live_bitmap.get());
220 }
221 }
222
Carl Shapiro69759ea2011-07-21 18:13:35 -0700223 // Allocate the initial mark bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800224 UniquePtr<HeapBitmap> mark_bitmap(HeapBitmap::Create("dalvik-bitmap-2", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700225 if (mark_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700226 LOG(FATAL) << "Failed to create mark bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700227 }
228
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800229 // Allocate the card table.
Ian Rogers30fab402012-01-23 15:43:46 -0800230 UniquePtr<CardTable> card_table(CardTable::Create(heap_begin, heap_capacity));
Ian Rogers5d76c432011-10-31 21:42:49 -0700231 if (card_table.get() == NULL) {
232 LOG(FATAL) << "Failed to create card table";
233 }
234
Carl Shapiro69759ea2011-07-21 18:13:35 -0700235 live_bitmap_ = live_bitmap.release();
236 mark_bitmap_ = mark_bitmap.release();
Ian Rogers5d76c432011-10-31 21:42:49 -0700237 card_table_ = card_table.release();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700238
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700239 num_bytes_allocated_ = 0;
240 num_objects_allocated_ = 0;
241
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800242 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700243 // but we can create the heap lock now. We don't create it earlier to
244 // make it clear that you can't use locks during heap initialization.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800245 lock_ = new Mutex("Heap lock", kHeapLock);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700246
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800247 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800248 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700249 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700250}
251
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800252void Heap::AddSpace(Space* space) {
253 spaces_.push_back(space);
254}
255
256Heap::~Heap() {
257 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800258 // We can't take the heap lock here because there might be a daemon thread suspended with the
259 // heap lock held. We know though that no non-daemon threads are executing, and we know that
260 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
261 // those threads can't resume. We're the only running thread, and we can do whatever we like...
Carl Shapiro58551df2011-07-24 03:09:51 -0700262 STLDeleteElements(&spaces_);
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800263 delete mark_bitmap_;
264 delete live_bitmap_;
265 delete card_table_;
266 delete lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700267}
268
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700269static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
270 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
271
272 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
273 size_t chunk_free_bytes = 0;
274 if (used_bytes < chunk_size) {
275 chunk_free_bytes = chunk_size - used_bytes;
276 }
277
278 if (chunk_free_bytes > max_contiguous_allocation) {
279 max_contiguous_allocation = chunk_free_bytes;
280 }
281}
282
283Object* Heap::AllocObject(Class* c, size_t byte_count) {
284 // Used in the detail message if we throw an OOME.
285 int64_t total_bytes_free;
286 size_t max_contiguous_allocation;
287
Elliott Hughes418dfe72011-10-06 18:56:27 -0700288 {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800289 ScopedHeapLock heap_lock;
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700290 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
291 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
292 strlen(ClassHelper(c).GetDescriptor()) == 0);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700293 DCHECK_GE(byte_count, sizeof(Object));
294 Object* obj = AllocateLocked(byte_count);
295 if (obj != NULL) {
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700296 obj->SetClass(c);
Elliott Hughes545a0642011-11-08 19:10:03 -0800297 if (Dbg::IsAllocTrackingEnabled()) {
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700298 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes545a0642011-11-08 19:10:03 -0800299 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700300 return obj;
301 }
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700302 total_bytes_free = GetFreeMemory();
303 max_contiguous_allocation = 0;
304 GetAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Carl Shapiro58551df2011-07-24 03:09:51 -0700305 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700306
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700307 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
308 byte_count,
309 PrettyDescriptor(c).c_str(),
310 total_bytes_free, max_contiguous_allocation));
311 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700312 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700313}
314
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700315bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700316 // Note: we deliberately don't take the lock here, and mustn't test anything that would
317 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700318 if (obj == NULL) {
319 return true;
320 }
321 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700322 return false;
323 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800324 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800325 if (spaces_[i]->Contains(obj)) {
326 return true;
327 }
328 }
329 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700330}
331
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700332bool Heap::IsLiveObjectLocked(const Object* obj) {
333 lock_->AssertHeld();
334 return IsHeapAddress(obj) && live_bitmap_->Test(obj);
335}
336
Elliott Hughes3e465b12011-09-02 18:26:12 -0700337#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338void Heap::VerifyObject(const Object* obj) {
jeffhao25045522012-03-13 19:34:37 -0700339 if (this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700340 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700341 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700342 return;
343 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800344 ScopedHeapLock heap_lock;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700345 Heap::VerifyObjectLocked(obj);
346}
347#endif
348
349void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700350 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700351 if (obj != NULL) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700352 if (!IsAligned<kObjectAlignment>(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700353 LOG(FATAL) << "Object isn't aligned: " << obj;
354 } else if (!live_bitmap_->Test(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 LOG(FATAL) << "Object is dead: " << obj;
356 }
357 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700358 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
360 Object::ClassOffset().Int32Value();
361 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
362 if (c == NULL) {
Elliott Hughes5d78d392011-12-13 16:53:05 -0800363 LOG(FATAL) << "Null class in object: " << obj;
Elliott Hughes06b37d92011-10-16 11:51:29 -0700364 } else if (!IsAligned<kObjectAlignment>(c)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700365 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
366 } else if (!live_bitmap_->Test(c)) {
367 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
368 }
369 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700370 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700371 // that we don't want to run
Ian Rogers30fab402012-01-23 15:43:46 -0800372 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700373 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
Ian Rogers30fab402012-01-23 15:43:46 -0800374 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700375 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
376 CHECK_EQ(c_c, c_c_c);
377 }
378 }
379}
380
Brian Carlstrom78128a62011-09-15 17:21:19 -0700381void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700382 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800383 reinterpret_cast<Heap*>(arg)->VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384}
385
386void Heap::VerifyHeap() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800387 ScopedHeapLock heap_lock;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800388 live_bitmap_->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389}
390
Ian Rogers30fab402012-01-23 15:43:46 -0800391void Heap::RecordAllocationLocked(AllocSpace* space, const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700392#ifndef NDEBUG
393 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700394 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700395 }
396#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700397 size_t size = space->AllocationSize(obj);
Elliott Hughes5d78d392011-12-13 16:53:05 -0800398 DCHECK_GT(size, 0u);
Carl Shapiro58551df2011-07-24 03:09:51 -0700399 num_bytes_allocated_ += size;
400 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700401
402 if (Runtime::Current()->HasStatsEnabled()) {
403 RuntimeStats* global_stats = Runtime::Current()->GetStats();
404 RuntimeStats* thread_stats = Thread::Current()->GetStats();
405 ++global_stats->allocated_objects;
406 ++thread_stats->allocated_objects;
407 global_stats->allocated_bytes += size;
408 thread_stats->allocated_bytes += size;
409 }
410
Carl Shapiro58551df2011-07-24 03:09:51 -0700411 live_bitmap_->Set(obj);
412}
413
Elliott Hughes307f75d2011-10-12 18:04:40 -0700414void Heap::RecordFreeLocked(size_t freed_objects, size_t freed_bytes) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700415 lock_->AssertHeld();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700416
417 if (freed_objects < num_objects_allocated_) {
418 num_objects_allocated_ -= freed_objects;
419 } else {
420 num_objects_allocated_ = 0;
421 }
422 if (freed_bytes < num_bytes_allocated_) {
423 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700424 } else {
425 num_bytes_allocated_ = 0;
426 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700427
428 if (Runtime::Current()->HasStatsEnabled()) {
429 RuntimeStats* global_stats = Runtime::Current()->GetStats();
430 RuntimeStats* thread_stats = Thread::Current()->GetStats();
431 ++global_stats->freed_objects;
432 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700433 global_stats->freed_bytes += freed_bytes;
434 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700435 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700436}
437
Elliott Hughes92b3b562011-09-08 16:32:26 -0700438Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700439 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700440 DCHECK(alloc_space_ != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800441 AllocSpace* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700442 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700443 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700444 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700445 }
446 return obj;
447}
448
Ian Rogers30fab402012-01-23 15:43:46 -0800449Object* Heap::AllocateLocked(AllocSpace* space, size_t alloc_size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700450 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700451
Brian Carlstromb82b6872011-10-26 17:18:07 -0700452 // Since allocation can cause a GC which will need to SuspendAll,
453 // make sure all allocators are in the kRunnable state.
Elliott Hughes34e06962012-04-09 13:55:55 -0700454 CHECK_EQ(Thread::Current()->GetState(), kRunnable);
Brian Carlstromb82b6872011-10-26 17:18:07 -0700455
Ian Rogers30fab402012-01-23 15:43:46 -0800456 // Fail impossible allocations
457 if (alloc_size > space->Capacity()) {
458 // On failure collect soft references
459 CollectGarbageInternal(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700460 return NULL;
461 }
462
Ian Rogers30fab402012-01-23 15:43:46 -0800463 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700464 if (ptr != NULL) {
465 return ptr;
466 }
467
Ian Rogers30fab402012-01-23 15:43:46 -0800468 // The allocation failed. If the GC is running, block until it completes and retry.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700469 if (is_gc_running_) {
Ian Rogers30fab402012-01-23 15:43:46 -0800470 // The GC is concurrently tracing the heap. Release the heap lock, wait for the GC to
471 // complete, and retrying allocating.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700472 WaitForConcurrentGcToComplete();
Ian Rogers30fab402012-01-23 15:43:46 -0800473 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700474 if (ptr != NULL) {
475 return ptr;
476 }
477 }
478
479 // Another failure. Our thread was starved or there may be too many
480 // live objects. Try a foreground GC. This will have no effect if
481 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700482 if (Runtime::Current()->HasStatsEnabled()) {
483 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
484 ++Thread::Current()->GetStats()->gc_for_alloc_count;
485 }
Ian Rogers30fab402012-01-23 15:43:46 -0800486 CollectGarbageInternal(false);
487 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700488 if (ptr != NULL) {
489 return ptr;
490 }
491
492 // Even that didn't work; this is an exceptional state.
493 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800494 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700495 if (ptr != NULL) {
496 //size_t new_footprint = dvmHeapSourceGetIdealFootprint();
Ian Rogers30fab402012-01-23 15:43:46 -0800497 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700498 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700499 // free space is equal to the old free space + the
500 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800501 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800502 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700503 return ptr;
504 }
505
Elliott Hughes81ff3182012-03-23 20:35:56 -0700506 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
507 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
508 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700509
Elliott Hughes418dfe72011-10-06 18:56:27 -0700510 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800511 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Ian Rogers30fab402012-01-23 15:43:46 -0800512 CollectGarbageInternal(true);
513 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700514 if (ptr != NULL) {
515 return ptr;
516 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700517
Carl Shapiro69759ea2011-07-21 18:13:35 -0700518 return NULL;
519}
520
Elliott Hughesbf86d042011-08-31 17:53:14 -0700521int64_t Heap::GetMaxMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800522 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700523}
524
525int64_t Heap::GetTotalMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800526 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700527}
528
529int64_t Heap::GetFreeMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800530 return alloc_space_->Capacity() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700531}
532
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700533class InstanceCounter {
534 public:
535 InstanceCounter(Class* c, bool count_assignable)
536 : class_(c), count_assignable_(count_assignable), count_(0) {
537 }
538
539 size_t GetCount() {
540 return count_;
541 }
542
543 static void Callback(Object* o, void* arg) {
544 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
545 }
546
547 private:
548 void VisitInstance(Object* o) {
549 Class* instance_class = o->GetClass();
550 if (count_assignable_) {
551 if (instance_class == class_) {
552 ++count_;
553 }
554 } else {
555 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
556 ++count_;
557 }
558 }
559 }
560
561 Class* class_;
562 bool count_assignable_;
563 size_t count_;
564};
565
566int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800567 ScopedHeapLock heap_lock;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700568 InstanceCounter counter(c, count_assignable);
569 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
570 return counter.GetCount();
571}
572
Ian Rogers30fab402012-01-23 15:43:46 -0800573void Heap::CollectGarbage(bool clear_soft_references) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800574 ScopedHeapLock heap_lock;
Ian Rogers30fab402012-01-23 15:43:46 -0800575 CollectGarbageInternal(clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700576}
577
Ian Rogers30fab402012-01-23 15:43:46 -0800578void Heap::CollectGarbageInternal(bool clear_soft_references) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700579 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700580
Elliott Hughes8d768a92011-09-14 16:35:25 -0700581 ThreadList* thread_list = Runtime::Current()->GetThreadList();
582 thread_list->SuspendAll();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700583
584 size_t initial_size = num_bytes_allocated_;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700585 TimingLogger timings("CollectGarbageInternal");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700586 uint64_t t0 = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700587 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700588 {
589 MarkSweep mark_sweep;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700590 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700591
592 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700593 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700594
595 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700596 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700597
Ian Rogers5d76c432011-10-31 21:42:49 -0700598 mark_sweep.ScanDirtyImageRoots();
599 timings.AddSplit("DirtyImageRoots");
600
601 // Roots are marked on the bitmap and the mark_stack is empty
602 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700603
604 // TODO: if concurrent
605 // unlock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700606 // thread_list->ResumeAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700607
Ian Rogers5d76c432011-10-31 21:42:49 -0700608 // Recursively mark all bits set in the non-image mark bitmap
Carl Shapiro58551df2011-07-24 03:09:51 -0700609 mark_sweep.RecursiveMark();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700610 timings.AddSplit("RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700611
612 // TODO: if concurrent
613 // lock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700614 // thread_list->SuspendAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700615 // re-mark root set
616 // scan dirty objects
617
Ian Rogers30fab402012-01-23 15:43:46 -0800618 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700619 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700620
Elliott Hughes2da50362011-10-10 16:57:08 -0700621 // TODO: if concurrent
622 // swap bitmaps
Carl Shapiro58551df2011-07-24 03:09:51 -0700623
624 mark_sweep.Sweep();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700625 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700626
627 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700628 }
629
630 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700631 timings.AddSplit("GrowForUtilization");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700632 uint64_t t1 = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700633 thread_list->ResumeAll();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700634
635 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800636 RequestHeapTrim();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700637
Ian Rogers3bb17a62012-01-27 23:56:44 -0800638 uint64_t duration_ns = t1 - t0;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800639 bool gc_was_particularly_slow = duration_ns > MsToNs(50); // TODO: crank this down for concurrent.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800640 if (VLOG_IS_ON(gc) || gc_was_particularly_slow) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800641 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
642 size_t bytes_freed = initial_size - num_bytes_allocated_;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800643 // lose low nanoseconds in duration. TODO: make this part of PrettyDuration
644 duration_ns = (duration_ns / 1000) * 1000;
Elliott Hughesc967f782012-04-16 10:23:15 -0700645 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
646 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
Ian Rogers3bb17a62012-01-27 23:56:44 -0800647 << "paused " << PrettyDuration(duration_ns);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700648 }
Elliott Hughes767a1472011-10-26 18:49:02 -0700649 Dbg::GcDidFinish();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800650 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700651 timings.Dump();
652 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700653}
654
655void Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700656 lock_->AssertHeld();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700657}
658
Elliott Hughesc967f782012-04-16 10:23:15 -0700659void Heap::DumpForSigQuit(std::ostream& os) {
660 os << "Heap: " << GetPercentFree() << "% free, "
661 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory())
Elliott Hughesae80b492012-04-24 10:43:17 -0700662 << "; " << num_objects_allocated_ << " objects\n";
Elliott Hughesc967f782012-04-16 10:23:15 -0700663}
664
665size_t Heap::GetPercentFree() {
666 size_t total = GetTotalMemory();
667 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
668}
669
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800670void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Ian Rogers30fab402012-01-23 15:43:46 -0800671 size_t alloc_space_capacity = alloc_space_->Capacity();
672 if (max_allowed_footprint > alloc_space_capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800673 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
674 << " to " << PrettySize(alloc_space_capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800675 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700676 }
Ian Rogers30fab402012-01-23 15:43:46 -0800677 alloc_space_->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700678}
679
Ian Rogers3bb17a62012-01-27 23:56:44 -0800680// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700681static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800682// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
683// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700684static const size_t kHeapMinFree = kHeapIdealFree / 4;
685
Carl Shapiro69759ea2011-07-21 18:13:35 -0700686void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700687 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700688
689 // We know what our utilization is at this moment.
690 // This doesn't actually resize any memory. It just lets the heap grow more
691 // when necessary.
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700692 size_t target_size(num_bytes_allocated_ / Heap::GetTargetHeapUtilization());
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700693
694 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
695 target_size = num_bytes_allocated_ + kHeapIdealFree;
696 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
697 target_size = num_bytes_allocated_ + kHeapMinFree;
698 }
699
700 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700701}
702
jeffhaoc1160702011-10-27 15:48:45 -0700703void Heap::ClearGrowthLimit() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800704 ScopedHeapLock heap_lock;
jeffhaoc1160702011-10-27 15:48:45 -0700705 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -0700706 alloc_space_->ClearGrowthLimit();
707}
708
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700709pid_t Heap::GetLockOwner() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700710 return lock_->GetOwner();
711}
712
Elliott Hughes92b3b562011-09-08 16:32:26 -0700713void Heap::Lock() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700714 // Grab the lock, but put ourselves into kVmWait if it looks
Brian Carlstromfad71432011-10-16 20:25:10 -0700715 // like we're going to have to wait on the mutex. This prevents
716 // deadlock if another thread is calling CollectGarbageInternal,
717 // since they will have the heap lock and be waiting for mutators to
718 // suspend.
719 if (!lock_->TryLock()) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700720 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Brian Carlstromfad71432011-10-16 20:25:10 -0700721 lock_->Lock();
722 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700723}
724
725void Heap::Unlock() {
726 lock_->Unlock();
727}
728
Elliott Hughesadb460d2011-10-05 17:02:34 -0700729void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
730 MemberOffset reference_queue_offset,
731 MemberOffset reference_queueNext_offset,
732 MemberOffset reference_pendingNext_offset,
733 MemberOffset finalizer_reference_zombie_offset) {
734 reference_referent_offset_ = reference_referent_offset;
735 reference_queue_offset_ = reference_queue_offset;
736 reference_queueNext_offset_ = reference_queueNext_offset;
737 reference_pendingNext_offset_ = reference_pendingNext_offset;
738 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
739 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
740 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
741 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
742 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
743 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
744}
745
746Object* Heap::GetReferenceReferent(Object* reference) {
747 DCHECK(reference != NULL);
748 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
749 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
750}
751
752void Heap::ClearReferenceReferent(Object* reference) {
753 DCHECK(reference != NULL);
754 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
755 reference->SetFieldObject(reference_referent_offset_, NULL, true);
756}
757
758// Returns true if the reference object has not yet been enqueued.
759bool Heap::IsEnqueuable(const Object* ref) {
760 DCHECK(ref != NULL);
761 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
762 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
763 return (queue != NULL) && (queue_next == NULL);
764}
765
766void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
767 DCHECK(ref != NULL);
768 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
769 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
770 EnqueuePendingReference(ref, cleared_reference_list);
771}
772
773void Heap::EnqueuePendingReference(Object* ref, Object** list) {
774 DCHECK(ref != NULL);
775 DCHECK(list != NULL);
776
777 if (*list == NULL) {
778 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
779 *list = ref;
780 } else {
781 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
782 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
783 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
784 }
785}
786
787Object* Heap::DequeuePendingReference(Object** list) {
788 DCHECK(list != NULL);
789 DCHECK(*list != NULL);
790 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
791 Object* ref;
792 if (*list == head) {
793 ref = *list;
794 *list = NULL;
795 } else {
796 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
797 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
798 ref = head;
799 }
800 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
801 return ref;
802}
803
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700804void Heap::AddFinalizerReference(Thread* self, Object* object) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700805 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughes77405792012-03-15 15:22:12 -0700806 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700807 args[0].SetL(object);
Elliott Hughesa4f94742012-05-29 16:28:38 -0700808 DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700809}
810
811void Heap::EnqueueClearedReferences(Object** cleared) {
812 DCHECK(cleared != NULL);
813 if (*cleared != NULL) {
Elliott Hughesadb460d2011-10-05 17:02:34 -0700814 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -0700815 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughes77405792012-03-15 15:22:12 -0700816 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700817 args[0].SetL(*cleared);
Elliott Hughesa4f94742012-05-29 16:28:38 -0700818 DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700819 *cleared = NULL;
820 }
821}
822
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800823void Heap::RequestHeapTrim() {
824 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
825 // because that only marks object heads, so a large array looks like lots of empty space. We
826 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
827 // to utilization (which is probably inversely proportional to how much benefit we can expect).
828 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
829 // not how much use we're making of those pages.
830 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
831 if (utilization > 0.75f) {
832 // Don't bother trimming the heap if it's more than 75% utilized.
833 // (This percentage was picked arbitrarily.)
834 return;
835 }
Ian Rogerse1d490c2012-02-03 09:09:07 -0800836 if (!Runtime::Current()->IsStarted()) {
837 // Heap trimming isn't supported without a Java runtime (such as at dex2oat time)
838 return;
839 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800840 JNIEnv* env = Thread::Current()->GetJniEnv();
Elliott Hugheseac76672012-05-24 21:56:51 -0700841 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800842 CHECK(!env->ExceptionCheck());
843}
844
Carl Shapiro69759ea2011-07-21 18:13:35 -0700845} // namespace art