blob: d2aada4053d44b7ceb07c558f886ed84ac2b5893 [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"
Carl Shapiro69759ea2011-07-21 18:13:35 -070038
39namespace art {
40
Ian Rogers30fab402012-01-23 15:43:46 -080041static void UpdateFirstAndLastSpace(Space** first_space, Space** last_space, Space* space) {
42 if (*first_space == NULL) {
43 *first_space = space;
44 *last_space = space;
45 } else {
46 if ((*first_space)->Begin() > space->Begin()) {
47 *first_space = space;
48 } else if (space->Begin() > (*last_space)->Begin()) {
49 *last_space = space;
50 }
51 }
52}
53
Elliott Hughesffb465f2012-03-01 18:46:05 -080054static bool GenerateImage(const std::string image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080055 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080056 std::vector<std::string> boot_class_path;
57 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070058 if (boot_class_path.empty()) {
59 LOG(FATAL) << "Failed to generate image because no boot class path specified";
60 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080061
62 std::vector<char*> arg_vector;
63
64 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070065 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080066 const char* dex2oat = dex2oat_string.c_str();
67 arg_vector.push_back(strdup(dex2oat));
68
69 std::string image_option_string("--image=");
70 image_option_string += image_file_name;
71 const char* image_option = image_option_string.c_str();
72 arg_vector.push_back(strdup(image_option));
73
74 arg_vector.push_back(strdup("--runtime-arg"));
75 arg_vector.push_back(strdup("-Xms64m"));
76
77 arg_vector.push_back(strdup("--runtime-arg"));
78 arg_vector.push_back(strdup("-Xmx64m"));
79
80 for (size_t i = 0; i < boot_class_path.size(); i++) {
81 std::string dex_file_option_string("--dex-file=");
82 dex_file_option_string += boot_class_path[i];
83 const char* dex_file_option = dex_file_option_string.c_str();
84 arg_vector.push_back(strdup(dex_file_option));
85 }
86
87 std::string oat_file_option_string("--oat-file=");
88 oat_file_option_string += image_file_name;
89 oat_file_option_string.erase(oat_file_option_string.size() - 3);
90 oat_file_option_string += "oat";
91 const char* oat_file_option = oat_file_option_string.c_str();
92 arg_vector.push_back(strdup(oat_file_option));
93
94 arg_vector.push_back(strdup("--base=0x60000000"));
95
Elliott Hughes48436bb2012-02-07 15:23:28 -080096 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080097 LOG(INFO) << command_line;
98
Elliott Hughes48436bb2012-02-07 15:23:28 -080099 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800100 char** argv = &arg_vector[0];
101
102 // fork and exec dex2oat
103 pid_t pid = fork();
104 if (pid == 0) {
105 // no allocation allowed between fork and exec
106
107 // change process groups, so we don't get reaped by ProcessManager
108 setpgid(0, 0);
109
110 execv(dex2oat, argv);
111
112 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
113 return false;
114 } else {
115 STLDeleteElements(&arg_vector);
116
117 // wait for dex2oat to finish
118 int status;
119 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
120 if (got_pid != pid) {
121 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
122 return false;
123 }
124 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
125 LOG(ERROR) << dex2oat << " failed: " << command_line;
126 return false;
127 }
128 }
129 return true;
130}
131
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800132Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
133 const std::string& original_image_file_name)
134 : lock_(NULL),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700135 image_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800136 alloc_space_(NULL),
137 mark_bitmap_(NULL),
138 live_bitmap_(NULL),
139 card_table_(NULL),
140 card_marking_disabled_(false),
141 is_gc_running_(false),
142 num_bytes_allocated_(0),
143 num_objects_allocated_(0),
144 java_lang_ref_FinalizerReference_(NULL),
145 java_lang_ref_ReferenceQueue_(NULL),
146 reference_referent_offset_(0),
147 reference_queue_offset_(0),
148 reference_queueNext_offset_(0),
149 reference_pendingNext_offset_(0),
150 finalizer_reference_zombie_offset_(0),
151 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700152 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800153 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800154 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700155 }
156
Ian Rogers30fab402012-01-23 15:43:46 -0800157 // Compute the bounds of all spaces for allocating live and mark bitmaps
158 // there will be at least one space (the alloc space)
159 Space* first_space = NULL;
160 Space* last_space = NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700161
Ian Rogers30fab402012-01-23 15:43:46 -0800162 // Requested begin for the alloc space, to follow the mapped image and oat files
163 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800164 std::string image_file_name(original_image_file_name);
165 if (!image_file_name.empty()) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800166 if (OS::FileExists(image_file_name.c_str())) {
167 // If the /system file exists, it should be up-to-date, don't try to generate
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700168 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800169 } else {
170 // If the /system file didn't exist, we need to use one from the art-cache.
171 // If the cache file exists, try to open, but if it fails, regenerate.
172 // If it does not exist, generate.
173 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
174 if (OS::FileExists(image_file_name.c_str())) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700175 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800176 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700177 if (image_space_ == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800178 if (!GenerateImage(image_file_name)) {
179 LOG(FATAL) << "Failed to generate image: " << image_file_name;
180 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700181 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800182 }
183 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700184 if (image_space_ == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800185 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700186 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800187
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700188 AddSpace(image_space_);
189 UpdateFirstAndLastSpace(&first_space, &last_space, image_space_);
Ian Rogers30fab402012-01-23 15:43:46 -0800190 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
191 // isn't going to get in the middle
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700192 byte* oat_end_addr = image_space_->GetImageHeader().GetOatEnd();
193 CHECK(oat_end_addr > image_space_->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800194 if (oat_end_addr > requested_begin) {
195 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
196 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700197 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700198 }
199
Ian Rogers30fab402012-01-23 15:43:46 -0800200 alloc_space_ = Space::CreateAllocSpace("alloc space", initial_size, growth_limit, capacity,
201 requested_begin);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700202 if (alloc_space_ == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700203 LOG(FATAL) << "Failed to create alloc space";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700204 }
Ian Rogers30fab402012-01-23 15:43:46 -0800205 AddSpace(alloc_space_);
206 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
207 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800208 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700209
210 // Allocate the initial live bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800211 UniquePtr<HeapBitmap> live_bitmap(HeapBitmap::Create("dalvik-bitmap-1", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700212 if (live_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700213 LOG(FATAL) << "Failed to create live bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700214 }
215
Ian Rogers30fab402012-01-23 15:43:46 -0800216 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800217 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800218 Space* space = spaces_[i];
219 if (space->IsImageSpace()) {
220 space->AsImageSpace()->RecordImageAllocations(live_bitmap.get());
221 }
222 }
223
Carl Shapiro69759ea2011-07-21 18:13:35 -0700224 // Allocate the initial mark bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800225 UniquePtr<HeapBitmap> mark_bitmap(HeapBitmap::Create("dalvik-bitmap-2", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700226 if (mark_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700227 LOG(FATAL) << "Failed to create mark bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700228 }
229
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800230 // Allocate the card table.
Ian Rogers30fab402012-01-23 15:43:46 -0800231 UniquePtr<CardTable> card_table(CardTable::Create(heap_begin, heap_capacity));
Ian Rogers5d76c432011-10-31 21:42:49 -0700232 if (card_table.get() == NULL) {
233 LOG(FATAL) << "Failed to create card table";
234 }
235
Carl Shapiro69759ea2011-07-21 18:13:35 -0700236 live_bitmap_ = live_bitmap.release();
237 mark_bitmap_ = mark_bitmap.release();
Ian Rogers5d76c432011-10-31 21:42:49 -0700238 card_table_ = card_table.release();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700239
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700240 num_bytes_allocated_ = 0;
241 num_objects_allocated_ = 0;
242
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800243 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700244 // but we can create the heap lock now. We don't create it earlier to
245 // make it clear that you can't use locks during heap initialization.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800246 lock_ = new Mutex("Heap lock", kHeapLock);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700247
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800248 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800249 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700250 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700251}
252
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800253void Heap::AddSpace(Space* space) {
254 spaces_.push_back(space);
255}
256
257Heap::~Heap() {
258 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800259 // We can't take the heap lock here because there might be a daemon thread suspended with the
260 // heap lock held. We know though that no non-daemon threads are executing, and we know that
261 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
262 // 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 -0700263 STLDeleteElements(&spaces_);
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800264 delete mark_bitmap_;
265 delete live_bitmap_;
266 delete card_table_;
267 delete lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700268}
269
Elliott Hughes418dfe72011-10-06 18:56:27 -0700270Object* Heap::AllocObject(Class* klass, size_t byte_count) {
271 {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800272 ScopedHeapLock heap_lock;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800273 DCHECK(klass == NULL || (klass->IsClassClass() && byte_count >= sizeof(Class)) ||
274 (klass->IsVariableSize() || klass->GetObjectSize() == byte_count) ||
Elliott Hughes91250e02011-12-13 22:30:35 -0800275 strlen(ClassHelper(klass).GetDescriptor()) == 0);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700276 DCHECK_GE(byte_count, sizeof(Object));
277 Object* obj = AllocateLocked(byte_count);
278 if (obj != NULL) {
279 obj->SetClass(klass);
Elliott Hughes545a0642011-11-08 19:10:03 -0800280 if (Dbg::IsAllocTrackingEnabled()) {
281 Dbg::RecordAllocation(klass, byte_count);
282 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700283 return obj;
284 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700285 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700286
287 Thread::Current()->ThrowOutOfMemoryError(klass, byte_count);
288 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700289}
290
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700291bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700292 // Note: we deliberately don't take the lock here, and mustn't test anything that would
293 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700294 if (obj == NULL) {
295 return true;
296 }
297 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700298 return false;
299 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800300 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800301 if (spaces_[i]->Contains(obj)) {
302 return true;
303 }
304 }
305 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700306}
307
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700308bool Heap::IsLiveObjectLocked(const Object* obj) {
309 lock_->AssertHeld();
310 return IsHeapAddress(obj) && live_bitmap_->Test(obj);
311}
312
Elliott Hughes3e465b12011-09-02 18:26:12 -0700313#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700314void Heap::VerifyObject(const Object* obj) {
jeffhao25045522012-03-13 19:34:37 -0700315 if (this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
316 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700317 return;
318 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800319 ScopedHeapLock heap_lock;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700320 Heap::VerifyObjectLocked(obj);
321}
322#endif
323
324void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700325 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700326 if (obj != NULL) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700327 if (!IsAligned<kObjectAlignment>(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700328 LOG(FATAL) << "Object isn't aligned: " << obj;
329 } else if (!live_bitmap_->Test(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700330 LOG(FATAL) << "Object is dead: " << obj;
331 }
332 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700333 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700334 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
335 Object::ClassOffset().Int32Value();
336 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
337 if (c == NULL) {
Elliott Hughes5d78d392011-12-13 16:53:05 -0800338 LOG(FATAL) << "Null class in object: " << obj;
Elliott Hughes06b37d92011-10-16 11:51:29 -0700339 } else if (!IsAligned<kObjectAlignment>(c)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700340 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
341 } else if (!live_bitmap_->Test(c)) {
342 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
343 }
344 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700345 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346 // that we don't want to run
Ian Rogers30fab402012-01-23 15:43:46 -0800347 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
Ian Rogers30fab402012-01-23 15:43:46 -0800349 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700350 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
351 CHECK_EQ(c_c, c_c_c);
352 }
353 }
354}
355
Brian Carlstrom78128a62011-09-15 17:21:19 -0700356void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800358 reinterpret_cast<Heap*>(arg)->VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359}
360
361void Heap::VerifyHeap() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800362 ScopedHeapLock heap_lock;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800363 live_bitmap_->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364}
365
Ian Rogers30fab402012-01-23 15:43:46 -0800366void Heap::RecordAllocationLocked(AllocSpace* space, const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700367#ifndef NDEBUG
368 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700369 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700370 }
371#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700372 size_t size = space->AllocationSize(obj);
Elliott Hughes5d78d392011-12-13 16:53:05 -0800373 DCHECK_GT(size, 0u);
Carl Shapiro58551df2011-07-24 03:09:51 -0700374 num_bytes_allocated_ += size;
375 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700376
377 if (Runtime::Current()->HasStatsEnabled()) {
378 RuntimeStats* global_stats = Runtime::Current()->GetStats();
379 RuntimeStats* thread_stats = Thread::Current()->GetStats();
380 ++global_stats->allocated_objects;
381 ++thread_stats->allocated_objects;
382 global_stats->allocated_bytes += size;
383 thread_stats->allocated_bytes += size;
384 }
385
Carl Shapiro58551df2011-07-24 03:09:51 -0700386 live_bitmap_->Set(obj);
387}
388
Elliott Hughes307f75d2011-10-12 18:04:40 -0700389void Heap::RecordFreeLocked(size_t freed_objects, size_t freed_bytes) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700390 lock_->AssertHeld();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700391
392 if (freed_objects < num_objects_allocated_) {
393 num_objects_allocated_ -= freed_objects;
394 } else {
395 num_objects_allocated_ = 0;
396 }
397 if (freed_bytes < num_bytes_allocated_) {
398 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700399 } else {
400 num_bytes_allocated_ = 0;
401 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700402
403 if (Runtime::Current()->HasStatsEnabled()) {
404 RuntimeStats* global_stats = Runtime::Current()->GetStats();
405 RuntimeStats* thread_stats = Thread::Current()->GetStats();
406 ++global_stats->freed_objects;
407 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700408 global_stats->freed_bytes += freed_bytes;
409 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700410 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700411}
412
Elliott Hughes92b3b562011-09-08 16:32:26 -0700413Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700414 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700415 DCHECK(alloc_space_ != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800416 AllocSpace* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700417 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700418 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700419 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700420 }
421 return obj;
422}
423
Ian Rogers30fab402012-01-23 15:43:46 -0800424Object* Heap::AllocateLocked(AllocSpace* space, size_t alloc_size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700425 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700426
Brian Carlstromb82b6872011-10-26 17:18:07 -0700427 // Since allocation can cause a GC which will need to SuspendAll,
428 // make sure all allocators are in the kRunnable state.
Ian Rogersf45b1542012-02-03 18:03:48 -0800429 CHECK_EQ(Thread::Current()->GetState(), Thread::kRunnable);
Brian Carlstromb82b6872011-10-26 17:18:07 -0700430
Ian Rogers30fab402012-01-23 15:43:46 -0800431 // Fail impossible allocations
432 if (alloc_size > space->Capacity()) {
433 // On failure collect soft references
434 CollectGarbageInternal(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700435 return NULL;
436 }
437
Ian Rogers30fab402012-01-23 15:43:46 -0800438 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700439 if (ptr != NULL) {
440 return ptr;
441 }
442
Ian Rogers30fab402012-01-23 15:43:46 -0800443 // The allocation failed. If the GC is running, block until it completes and retry.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700444 if (is_gc_running_) {
Ian Rogers30fab402012-01-23 15:43:46 -0800445 // The GC is concurrently tracing the heap. Release the heap lock, wait for the GC to
446 // complete, and retrying allocating.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700447 WaitForConcurrentGcToComplete();
Ian Rogers30fab402012-01-23 15:43:46 -0800448 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700449 if (ptr != NULL) {
450 return ptr;
451 }
452 }
453
454 // Another failure. Our thread was starved or there may be too many
455 // live objects. Try a foreground GC. This will have no effect if
456 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700457 if (Runtime::Current()->HasStatsEnabled()) {
458 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
459 ++Thread::Current()->GetStats()->gc_for_alloc_count;
460 }
Ian Rogers30fab402012-01-23 15:43:46 -0800461 CollectGarbageInternal(false);
462 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700463 if (ptr != NULL) {
464 return ptr;
465 }
466
467 // Even that didn't work; this is an exceptional state.
468 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800469 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700470 if (ptr != NULL) {
471 //size_t new_footprint = dvmHeapSourceGetIdealFootprint();
Ian Rogers30fab402012-01-23 15:43:46 -0800472 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700473 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700474 // free space is equal to the old free space + the
475 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800476 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800477 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700478 return ptr;
479 }
480
Elliott Hughes81ff3182012-03-23 20:35:56 -0700481 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
482 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
483 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700484
Elliott Hughes418dfe72011-10-06 18:56:27 -0700485 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800486 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Ian Rogers30fab402012-01-23 15:43:46 -0800487 CollectGarbageInternal(true);
488 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700489 if (ptr != NULL) {
490 return ptr;
491 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700492
Ian Rogers3bb17a62012-01-27 23:56:44 -0800493 LOG(ERROR) << "Out of memory on a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700494
Carl Shapiro58551df2011-07-24 03:09:51 -0700495 // TODO: tell the HeapSource to dump its state
496 // TODO: dump stack traces for all threads
Carl Shapiro69759ea2011-07-21 18:13:35 -0700497
Carl Shapiro69759ea2011-07-21 18:13:35 -0700498 return NULL;
499}
500
Elliott Hughesbf86d042011-08-31 17:53:14 -0700501int64_t Heap::GetMaxMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800502 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700503}
504
505int64_t Heap::GetTotalMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800506 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700507}
508
509int64_t Heap::GetFreeMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800510 return alloc_space_->Capacity() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700511}
512
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700513class InstanceCounter {
514 public:
515 InstanceCounter(Class* c, bool count_assignable)
516 : class_(c), count_assignable_(count_assignable), count_(0) {
517 }
518
519 size_t GetCount() {
520 return count_;
521 }
522
523 static void Callback(Object* o, void* arg) {
524 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
525 }
526
527 private:
528 void VisitInstance(Object* o) {
529 Class* instance_class = o->GetClass();
530 if (count_assignable_) {
531 if (instance_class == class_) {
532 ++count_;
533 }
534 } else {
535 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
536 ++count_;
537 }
538 }
539 }
540
541 Class* class_;
542 bool count_assignable_;
543 size_t count_;
544};
545
546int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800547 ScopedHeapLock heap_lock;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700548 InstanceCounter counter(c, count_assignable);
549 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
550 return counter.GetCount();
551}
552
Ian Rogers30fab402012-01-23 15:43:46 -0800553void Heap::CollectGarbage(bool clear_soft_references) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800554 ScopedHeapLock heap_lock;
Ian Rogers30fab402012-01-23 15:43:46 -0800555 CollectGarbageInternal(clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700556}
557
Ian Rogers30fab402012-01-23 15:43:46 -0800558void Heap::CollectGarbageInternal(bool clear_soft_references) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700559 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700560
Elliott Hughes8d768a92011-09-14 16:35:25 -0700561 ThreadList* thread_list = Runtime::Current()->GetThreadList();
562 thread_list->SuspendAll();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700563
564 size_t initial_size = num_bytes_allocated_;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700565 TimingLogger timings("CollectGarbageInternal");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700566 uint64_t t0 = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700567 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700568 {
569 MarkSweep mark_sweep;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700570 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700571
572 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700573 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700574
575 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700576 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700577
Ian Rogers5d76c432011-10-31 21:42:49 -0700578 mark_sweep.ScanDirtyImageRoots();
579 timings.AddSplit("DirtyImageRoots");
580
581 // Roots are marked on the bitmap and the mark_stack is empty
582 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700583
584 // TODO: if concurrent
585 // unlock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700586 // thread_list->ResumeAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700587
Ian Rogers5d76c432011-10-31 21:42:49 -0700588 // Recursively mark all bits set in the non-image mark bitmap
Carl Shapiro58551df2011-07-24 03:09:51 -0700589 mark_sweep.RecursiveMark();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700590 timings.AddSplit("RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700591
592 // TODO: if concurrent
593 // lock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700594 // thread_list->SuspendAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700595 // re-mark root set
596 // scan dirty objects
597
Ian Rogers30fab402012-01-23 15:43:46 -0800598 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700599 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700600
Elliott Hughes2da50362011-10-10 16:57:08 -0700601 // TODO: if concurrent
602 // swap bitmaps
Carl Shapiro58551df2011-07-24 03:09:51 -0700603
604 mark_sweep.Sweep();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700605 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700606
607 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700608 }
609
610 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700611 timings.AddSplit("GrowForUtilization");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700612 uint64_t t1 = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700613 thread_list->ResumeAll();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700614
615 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800616 RequestHeapTrim();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700617
Ian Rogers3bb17a62012-01-27 23:56:44 -0800618 uint64_t duration_ns = t1 - t0;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800619 bool gc_was_particularly_slow = duration_ns > MsToNs(50); // TODO: crank this down for concurrent.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800620 if (VLOG_IS_ON(gc) || gc_was_particularly_slow) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800621 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
622 size_t bytes_freed = initial_size - num_bytes_allocated_;
623 if (bytes_freed > KB) { // ignore freed bytes in output if > 1KB
624 bytes_freed = RoundDown(bytes_freed, KB);
625 }
626 size_t bytes_allocated = RoundUp(num_bytes_allocated_, KB);
627 // lose low nanoseconds in duration. TODO: make this part of PrettyDuration
628 duration_ns = (duration_ns / 1000) * 1000;
629 size_t total = GetTotalMemory();
630 size_t percentFree = 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
631 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << percentFree << "% free, "
632 << PrettySize(bytes_allocated) << "/" << PrettySize(total) << ", "
633 << "paused " << PrettyDuration(duration_ns);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700634 }
Elliott Hughes767a1472011-10-26 18:49:02 -0700635 Dbg::GcDidFinish();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800636 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700637 timings.Dump();
638 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700639}
640
641void Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700642 lock_->AssertHeld();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700643}
644
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800645void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Ian Rogers30fab402012-01-23 15:43:46 -0800646 size_t alloc_space_capacity = alloc_space_->Capacity();
647 if (max_allowed_footprint > alloc_space_capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800648 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
649 << " to " << PrettySize(alloc_space_capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800650 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700651 }
Ian Rogers30fab402012-01-23 15:43:46 -0800652 alloc_space_->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700653}
654
Ian Rogers3bb17a62012-01-27 23:56:44 -0800655// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700656static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800657// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
658// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700659static const size_t kHeapMinFree = kHeapIdealFree / 4;
660
Carl Shapiro69759ea2011-07-21 18:13:35 -0700661void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700662 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700663
664 // We know what our utilization is at this moment.
665 // This doesn't actually resize any memory. It just lets the heap grow more
666 // when necessary.
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700667 size_t target_size(num_bytes_allocated_ / Heap::GetTargetHeapUtilization());
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700668
669 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
670 target_size = num_bytes_allocated_ + kHeapIdealFree;
671 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
672 target_size = num_bytes_allocated_ + kHeapMinFree;
673 }
674
675 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700676}
677
jeffhaoc1160702011-10-27 15:48:45 -0700678void Heap::ClearGrowthLimit() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800679 ScopedHeapLock heap_lock;
jeffhaoc1160702011-10-27 15:48:45 -0700680 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -0700681 alloc_space_->ClearGrowthLimit();
682}
683
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700684pid_t Heap::GetLockOwner() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700685 return lock_->GetOwner();
686}
687
Elliott Hughes92b3b562011-09-08 16:32:26 -0700688void Heap::Lock() {
Brian Carlstromfad71432011-10-16 20:25:10 -0700689 // Grab the lock, but put ourselves into Thread::kVmWait if it looks
690 // like we're going to have to wait on the mutex. This prevents
691 // deadlock if another thread is calling CollectGarbageInternal,
692 // since they will have the heap lock and be waiting for mutators to
693 // suspend.
694 if (!lock_->TryLock()) {
695 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
696 lock_->Lock();
697 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700698}
699
700void Heap::Unlock() {
701 lock_->Unlock();
702}
703
Elliott Hughesadb460d2011-10-05 17:02:34 -0700704void Heap::SetWellKnownClasses(Class* java_lang_ref_FinalizerReference,
705 Class* java_lang_ref_ReferenceQueue) {
706 java_lang_ref_FinalizerReference_ = java_lang_ref_FinalizerReference;
707 java_lang_ref_ReferenceQueue_ = java_lang_ref_ReferenceQueue;
708 CHECK(java_lang_ref_FinalizerReference_ != NULL);
709 CHECK(java_lang_ref_ReferenceQueue_ != NULL);
710}
711
712void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
713 MemberOffset reference_queue_offset,
714 MemberOffset reference_queueNext_offset,
715 MemberOffset reference_pendingNext_offset,
716 MemberOffset finalizer_reference_zombie_offset) {
717 reference_referent_offset_ = reference_referent_offset;
718 reference_queue_offset_ = reference_queue_offset;
719 reference_queueNext_offset_ = reference_queueNext_offset;
720 reference_pendingNext_offset_ = reference_pendingNext_offset;
721 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
722 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
723 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
724 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
725 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
726 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
727}
728
729Object* Heap::GetReferenceReferent(Object* reference) {
730 DCHECK(reference != NULL);
731 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
732 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
733}
734
735void Heap::ClearReferenceReferent(Object* reference) {
736 DCHECK(reference != NULL);
737 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
738 reference->SetFieldObject(reference_referent_offset_, NULL, true);
739}
740
741// Returns true if the reference object has not yet been enqueued.
742bool Heap::IsEnqueuable(const Object* ref) {
743 DCHECK(ref != NULL);
744 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
745 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
746 return (queue != NULL) && (queue_next == NULL);
747}
748
749void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
750 DCHECK(ref != NULL);
751 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
752 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
753 EnqueuePendingReference(ref, cleared_reference_list);
754}
755
756void Heap::EnqueuePendingReference(Object* ref, Object** list) {
757 DCHECK(ref != NULL);
758 DCHECK(list != NULL);
759
760 if (*list == NULL) {
761 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
762 *list = ref;
763 } else {
764 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
765 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
766 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
767 }
768}
769
770Object* Heap::DequeuePendingReference(Object** list) {
771 DCHECK(list != NULL);
772 DCHECK(*list != NULL);
773 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
774 Object* ref;
775 if (*list == head) {
776 ref = *list;
777 *list = NULL;
778 } else {
779 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
780 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
781 ref = head;
782 }
783 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
784 return ref;
785}
786
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700787void Heap::AddFinalizerReference(Thread* self, Object* object) {
788 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700789 static Method* FinalizerReference_add =
790 java_lang_ref_FinalizerReference_->FindDirectMethod("add", "(Ljava/lang/Object;)V");
791 DCHECK(FinalizerReference_add != NULL);
Elliott Hughes77405792012-03-15 15:22:12 -0700792 JValue args[1];
793 args[0].l = object;
794 FinalizerReference_add->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700795}
796
797void Heap::EnqueueClearedReferences(Object** cleared) {
798 DCHECK(cleared != NULL);
799 if (*cleared != NULL) {
800 static Method* ReferenceQueue_add =
801 java_lang_ref_ReferenceQueue_->FindDirectMethod("add", "(Ljava/lang/ref/Reference;)V");
802 DCHECK(ReferenceQueue_add != NULL);
803
804 Thread* self = Thread::Current();
805 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Elliott Hughes77405792012-03-15 15:22:12 -0700806 JValue args[1];
807 args[0].l = *cleared;
808 ReferenceQueue_add->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700809 *cleared = NULL;
810 }
811}
812
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800813void Heap::RequestHeapTrim() {
814 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
815 // because that only marks object heads, so a large array looks like lots of empty space. We
816 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
817 // to utilization (which is probably inversely proportional to how much benefit we can expect).
818 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
819 // not how much use we're making of those pages.
820 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
821 if (utilization > 0.75f) {
822 // Don't bother trimming the heap if it's more than 75% utilized.
823 // (This percentage was picked arbitrarily.)
824 return;
825 }
Ian Rogerse1d490c2012-02-03 09:09:07 -0800826 if (!Runtime::Current()->IsStarted()) {
827 // Heap trimming isn't supported without a Java runtime (such as at dex2oat time)
828 return;
829 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800830 JNIEnv* env = Thread::Current()->GetJniEnv();
831 static jclass Daemons_class = CacheClass(env, "java/lang/Daemons");
832 static jmethodID Daemons_requestHeapTrim = env->GetStaticMethodID(Daemons_class, "requestHeapTrim", "()V");
833 env->CallStaticVoidMethod(Daemons_class, Daemons_requestHeapTrim);
834 CHECK(!env->ExceptionCheck());
835}
836
Carl Shapiro69759ea2011-07-21 18:13:35 -0700837} // namespace art