blob: b12ff2d5ae1c459d006573d92f00b301a3be9b21 [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());
65 dex2oat_string += "/bin/dex2oat";
66#ifndef NDEBUG
67 dex2oat_string += 'd';
68#endif
69 const char* dex2oat = dex2oat_string.c_str();
70 arg_vector.push_back(strdup(dex2oat));
71
72 std::string image_option_string("--image=");
73 image_option_string += image_file_name;
74 const char* image_option = image_option_string.c_str();
75 arg_vector.push_back(strdup(image_option));
76
77 arg_vector.push_back(strdup("--runtime-arg"));
78 arg_vector.push_back(strdup("-Xms64m"));
79
80 arg_vector.push_back(strdup("--runtime-arg"));
81 arg_vector.push_back(strdup("-Xmx64m"));
82
83 for (size_t i = 0; i < boot_class_path.size(); i++) {
84 std::string dex_file_option_string("--dex-file=");
85 dex_file_option_string += boot_class_path[i];
86 const char* dex_file_option = dex_file_option_string.c_str();
87 arg_vector.push_back(strdup(dex_file_option));
88 }
89
90 std::string oat_file_option_string("--oat-file=");
91 oat_file_option_string += image_file_name;
92 oat_file_option_string.erase(oat_file_option_string.size() - 3);
93 oat_file_option_string += "oat";
94 const char* oat_file_option = oat_file_option_string.c_str();
95 arg_vector.push_back(strdup(oat_file_option));
96
97 arg_vector.push_back(strdup("--base=0x60000000"));
98
Elliott Hughes48436bb2012-02-07 15:23:28 -080099 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800100 LOG(INFO) << command_line;
101
Elliott Hughes48436bb2012-02-07 15:23:28 -0800102 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800103 char** argv = &arg_vector[0];
104
105 // fork and exec dex2oat
106 pid_t pid = fork();
107 if (pid == 0) {
108 // no allocation allowed between fork and exec
109
110 // change process groups, so we don't get reaped by ProcessManager
111 setpgid(0, 0);
112
113 execv(dex2oat, argv);
114
115 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
116 return false;
117 } else {
118 STLDeleteElements(&arg_vector);
119
120 // wait for dex2oat to finish
121 int status;
122 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
123 if (got_pid != pid) {
124 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
125 return false;
126 }
127 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
128 LOG(ERROR) << dex2oat << " failed: " << command_line;
129 return false;
130 }
131 }
132 return true;
133}
134
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800135Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
136 const std::string& original_image_file_name)
137 : lock_(NULL),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700138 image_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800139 alloc_space_(NULL),
140 mark_bitmap_(NULL),
141 live_bitmap_(NULL),
142 card_table_(NULL),
143 card_marking_disabled_(false),
144 is_gc_running_(false),
145 num_bytes_allocated_(0),
146 num_objects_allocated_(0),
147 java_lang_ref_FinalizerReference_(NULL),
148 java_lang_ref_ReferenceQueue_(NULL),
149 reference_referent_offset_(0),
150 reference_queue_offset_(0),
151 reference_queueNext_offset_(0),
152 reference_pendingNext_offset_(0),
153 finalizer_reference_zombie_offset_(0),
154 target_utilization_(0.5),
155 verify_objects_(false)
156{
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800157 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800158 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700159 }
160
Ian Rogers30fab402012-01-23 15:43:46 -0800161 // Compute the bounds of all spaces for allocating live and mark bitmaps
162 // there will be at least one space (the alloc space)
163 Space* first_space = NULL;
164 Space* last_space = NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700165
Ian Rogers30fab402012-01-23 15:43:46 -0800166 // Requested begin for the alloc space, to follow the mapped image and oat files
167 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800168 std::string image_file_name(original_image_file_name);
169 if (!image_file_name.empty()) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800170 if (OS::FileExists(image_file_name.c_str())) {
171 // If the /system file exists, it should be up-to-date, don't try to generate
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700172 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800173 } else {
174 // If the /system file didn't exist, we need to use one from the art-cache.
175 // If the cache file exists, try to open, but if it fails, regenerate.
176 // If it does not exist, generate.
177 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
178 if (OS::FileExists(image_file_name.c_str())) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700179 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800180 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700181 if (image_space_ == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800182 if (!GenerateImage(image_file_name)) {
183 LOG(FATAL) << "Failed to generate image: " << image_file_name;
184 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700185 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800186 }
187 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700188 if (image_space_ == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800189 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700190 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800191
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700192 AddSpace(image_space_);
193 UpdateFirstAndLastSpace(&first_space, &last_space, image_space_);
Ian Rogers30fab402012-01-23 15:43:46 -0800194 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
195 // isn't going to get in the middle
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700196 byte* oat_end_addr = image_space_->GetImageHeader().GetOatEnd();
197 CHECK(oat_end_addr > image_space_->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800198 if (oat_end_addr > requested_begin) {
199 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
200 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700201 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700202 }
203
Ian Rogers30fab402012-01-23 15:43:46 -0800204 alloc_space_ = Space::CreateAllocSpace("alloc space", initial_size, growth_limit, capacity,
205 requested_begin);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700206 if (alloc_space_ == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700207 LOG(FATAL) << "Failed to create alloc space";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700208 }
Ian Rogers30fab402012-01-23 15:43:46 -0800209 AddSpace(alloc_space_);
210 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
211 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800212 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700213
214 // Allocate the initial live bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800215 UniquePtr<HeapBitmap> live_bitmap(HeapBitmap::Create("dalvik-bitmap-1", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700216 if (live_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700217 LOG(FATAL) << "Failed to create live bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700218 }
219
Ian Rogers30fab402012-01-23 15:43:46 -0800220 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800221 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800222 Space* space = spaces_[i];
223 if (space->IsImageSpace()) {
224 space->AsImageSpace()->RecordImageAllocations(live_bitmap.get());
225 }
226 }
227
Carl Shapiro69759ea2011-07-21 18:13:35 -0700228 // Allocate the initial mark bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800229 UniquePtr<HeapBitmap> mark_bitmap(HeapBitmap::Create("dalvik-bitmap-2", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700230 if (mark_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700231 LOG(FATAL) << "Failed to create mark bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700232 }
233
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800234 // Allocate the card table.
Ian Rogers30fab402012-01-23 15:43:46 -0800235 UniquePtr<CardTable> card_table(CardTable::Create(heap_begin, heap_capacity));
Ian Rogers5d76c432011-10-31 21:42:49 -0700236 if (card_table.get() == NULL) {
237 LOG(FATAL) << "Failed to create card table";
238 }
239
Carl Shapiro69759ea2011-07-21 18:13:35 -0700240 live_bitmap_ = live_bitmap.release();
241 mark_bitmap_ = mark_bitmap.release();
Ian Rogers5d76c432011-10-31 21:42:49 -0700242 card_table_ = card_table.release();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700243
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700244 num_bytes_allocated_ = 0;
245 num_objects_allocated_ = 0;
246
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800247 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700248 // but we can create the heap lock now. We don't create it earlier to
249 // make it clear that you can't use locks during heap initialization.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800250 lock_ = new Mutex("Heap lock", kHeapLock);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700251
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800252 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800253 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700254 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700255}
256
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800257void Heap::AddSpace(Space* space) {
258 spaces_.push_back(space);
259}
260
261Heap::~Heap() {
262 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800263 // We can't take the heap lock here because there might be a daemon thread suspended with the
264 // heap lock held. We know though that no non-daemon threads are executing, and we know that
265 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
266 // 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 -0700267 STLDeleteElements(&spaces_);
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800268 delete mark_bitmap_;
269 delete live_bitmap_;
270 delete card_table_;
271 delete lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700272}
273
Elliott Hughes418dfe72011-10-06 18:56:27 -0700274Object* Heap::AllocObject(Class* klass, size_t byte_count) {
275 {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800276 ScopedHeapLock heap_lock;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800277 DCHECK(klass == NULL || (klass->IsClassClass() && byte_count >= sizeof(Class)) ||
278 (klass->IsVariableSize() || klass->GetObjectSize() == byte_count) ||
Elliott Hughes91250e02011-12-13 22:30:35 -0800279 strlen(ClassHelper(klass).GetDescriptor()) == 0);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700280 DCHECK_GE(byte_count, sizeof(Object));
281 Object* obj = AllocateLocked(byte_count);
282 if (obj != NULL) {
283 obj->SetClass(klass);
Elliott Hughes545a0642011-11-08 19:10:03 -0800284 if (Dbg::IsAllocTrackingEnabled()) {
285 Dbg::RecordAllocation(klass, byte_count);
286 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700287 return obj;
288 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700289 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700290
291 Thread::Current()->ThrowOutOfMemoryError(klass, byte_count);
292 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700293}
294
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700295bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700296 // Note: we deliberately don't take the lock here, and mustn't test anything that would
297 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700298 if (obj == NULL) {
299 return true;
300 }
301 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700302 return false;
303 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800304 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800305 if (spaces_[i]->Contains(obj)) {
306 return true;
307 }
308 }
309 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700310}
311
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700312bool Heap::IsLiveObjectLocked(const Object* obj) {
313 lock_->AssertHeld();
314 return IsHeapAddress(obj) && live_bitmap_->Test(obj);
315}
316
Elliott Hughes3e465b12011-09-02 18:26:12 -0700317#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700318void Heap::VerifyObject(const Object* obj) {
jeffhao25045522012-03-13 19:34:37 -0700319 if (this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
320 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700321 return;
322 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800323 ScopedHeapLock heap_lock;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700324 Heap::VerifyObjectLocked(obj);
325}
326#endif
327
328void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700329 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700330 if (obj != NULL) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700331 if (!IsAligned<kObjectAlignment>(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332 LOG(FATAL) << "Object isn't aligned: " << obj;
333 } else if (!live_bitmap_->Test(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700334 LOG(FATAL) << "Object is dead: " << obj;
335 }
336 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700337 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
339 Object::ClassOffset().Int32Value();
340 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
341 if (c == NULL) {
Elliott Hughes5d78d392011-12-13 16:53:05 -0800342 LOG(FATAL) << "Null class in object: " << obj;
Elliott Hughes06b37d92011-10-16 11:51:29 -0700343 } else if (!IsAligned<kObjectAlignment>(c)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
345 } else if (!live_bitmap_->Test(c)) {
346 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
347 }
348 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700349 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700350 // that we don't want to run
Ian Rogers30fab402012-01-23 15:43:46 -0800351 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700352 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
Ian Rogers30fab402012-01-23 15:43:46 -0800353 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
355 CHECK_EQ(c_c, c_c_c);
356 }
357 }
358}
359
Brian Carlstrom78128a62011-09-15 17:21:19 -0700360void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700361 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800362 reinterpret_cast<Heap*>(arg)->VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363}
364
365void Heap::VerifyHeap() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800366 ScopedHeapLock heap_lock;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800367 live_bitmap_->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368}
369
Ian Rogers30fab402012-01-23 15:43:46 -0800370void Heap::RecordAllocationLocked(AllocSpace* space, const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700371#ifndef NDEBUG
372 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700373 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700374 }
375#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700376 size_t size = space->AllocationSize(obj);
Elliott Hughes5d78d392011-12-13 16:53:05 -0800377 DCHECK_GT(size, 0u);
Carl Shapiro58551df2011-07-24 03:09:51 -0700378 num_bytes_allocated_ += size;
379 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700380
381 if (Runtime::Current()->HasStatsEnabled()) {
382 RuntimeStats* global_stats = Runtime::Current()->GetStats();
383 RuntimeStats* thread_stats = Thread::Current()->GetStats();
384 ++global_stats->allocated_objects;
385 ++thread_stats->allocated_objects;
386 global_stats->allocated_bytes += size;
387 thread_stats->allocated_bytes += size;
388 }
389
Carl Shapiro58551df2011-07-24 03:09:51 -0700390 live_bitmap_->Set(obj);
391}
392
Elliott Hughes307f75d2011-10-12 18:04:40 -0700393void Heap::RecordFreeLocked(size_t freed_objects, size_t freed_bytes) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700394 lock_->AssertHeld();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700395
396 if (freed_objects < num_objects_allocated_) {
397 num_objects_allocated_ -= freed_objects;
398 } else {
399 num_objects_allocated_ = 0;
400 }
401 if (freed_bytes < num_bytes_allocated_) {
402 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700403 } else {
404 num_bytes_allocated_ = 0;
405 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700406
407 if (Runtime::Current()->HasStatsEnabled()) {
408 RuntimeStats* global_stats = Runtime::Current()->GetStats();
409 RuntimeStats* thread_stats = Thread::Current()->GetStats();
410 ++global_stats->freed_objects;
411 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700412 global_stats->freed_bytes += freed_bytes;
413 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700414 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700415}
416
Elliott Hughes92b3b562011-09-08 16:32:26 -0700417Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700418 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700419 DCHECK(alloc_space_ != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800420 AllocSpace* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700421 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700422 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700423 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700424 }
425 return obj;
426}
427
Ian Rogers30fab402012-01-23 15:43:46 -0800428Object* Heap::AllocateLocked(AllocSpace* space, size_t alloc_size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700429 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700430
Brian Carlstromb82b6872011-10-26 17:18:07 -0700431 // Since allocation can cause a GC which will need to SuspendAll,
432 // make sure all allocators are in the kRunnable state.
Ian Rogersf45b1542012-02-03 18:03:48 -0800433 CHECK_EQ(Thread::Current()->GetState(), Thread::kRunnable);
Brian Carlstromb82b6872011-10-26 17:18:07 -0700434
Ian Rogers30fab402012-01-23 15:43:46 -0800435 // Fail impossible allocations
436 if (alloc_size > space->Capacity()) {
437 // On failure collect soft references
438 CollectGarbageInternal(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700439 return NULL;
440 }
441
Ian Rogers30fab402012-01-23 15:43:46 -0800442 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700443 if (ptr != NULL) {
444 return ptr;
445 }
446
Ian Rogers30fab402012-01-23 15:43:46 -0800447 // The allocation failed. If the GC is running, block until it completes and retry.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700448 if (is_gc_running_) {
Ian Rogers30fab402012-01-23 15:43:46 -0800449 // The GC is concurrently tracing the heap. Release the heap lock, wait for the GC to
450 // complete, and retrying allocating.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700451 WaitForConcurrentGcToComplete();
Ian Rogers30fab402012-01-23 15:43:46 -0800452 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700453 if (ptr != NULL) {
454 return ptr;
455 }
456 }
457
458 // Another failure. Our thread was starved or there may be too many
459 // live objects. Try a foreground GC. This will have no effect if
460 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700461 if (Runtime::Current()->HasStatsEnabled()) {
462 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
463 ++Thread::Current()->GetStats()->gc_for_alloc_count;
464 }
Ian Rogers30fab402012-01-23 15:43:46 -0800465 CollectGarbageInternal(false);
466 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700467 if (ptr != NULL) {
468 return ptr;
469 }
470
471 // Even that didn't work; this is an exceptional state.
472 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800473 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700474 if (ptr != NULL) {
475 //size_t new_footprint = dvmHeapSourceGetIdealFootprint();
Ian Rogers30fab402012-01-23 15:43:46 -0800476 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700477 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700478 // free space is equal to the old free space + the
479 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800480 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800481 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700482 return ptr;
483 }
484
485 // Most allocations should have succeeded by now, so the heap is
486 // really full, really fragmented, or the requested size is really
487 // big. Do another GC, collecting SoftReferences this time. The VM
488 // spec requires that all SoftReferences have been collected and
489 // cleared before throwing an OOME.
490
Elliott Hughes418dfe72011-10-06 18:56:27 -0700491 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800492 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Ian Rogers30fab402012-01-23 15:43:46 -0800493 CollectGarbageInternal(true);
494 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700495 if (ptr != NULL) {
496 return ptr;
497 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700498
Ian Rogers3bb17a62012-01-27 23:56:44 -0800499 LOG(ERROR) << "Out of memory on a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700500
Carl Shapiro58551df2011-07-24 03:09:51 -0700501 // TODO: tell the HeapSource to dump its state
502 // TODO: dump stack traces for all threads
Carl Shapiro69759ea2011-07-21 18:13:35 -0700503
Carl Shapiro69759ea2011-07-21 18:13:35 -0700504 return NULL;
505}
506
Elliott Hughesbf86d042011-08-31 17:53:14 -0700507int64_t Heap::GetMaxMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800508 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700509}
510
511int64_t Heap::GetTotalMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800512 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700513}
514
515int64_t Heap::GetFreeMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800516 return alloc_space_->Capacity() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700517}
518
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700519class InstanceCounter {
520 public:
521 InstanceCounter(Class* c, bool count_assignable)
522 : class_(c), count_assignable_(count_assignable), count_(0) {
523 }
524
525 size_t GetCount() {
526 return count_;
527 }
528
529 static void Callback(Object* o, void* arg) {
530 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
531 }
532
533 private:
534 void VisitInstance(Object* o) {
535 Class* instance_class = o->GetClass();
536 if (count_assignable_) {
537 if (instance_class == class_) {
538 ++count_;
539 }
540 } else {
541 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
542 ++count_;
543 }
544 }
545 }
546
547 Class* class_;
548 bool count_assignable_;
549 size_t count_;
550};
551
552int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800553 ScopedHeapLock heap_lock;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700554 InstanceCounter counter(c, count_assignable);
555 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
556 return counter.GetCount();
557}
558
Ian Rogers30fab402012-01-23 15:43:46 -0800559void Heap::CollectGarbage(bool clear_soft_references) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800560 ScopedHeapLock heap_lock;
Ian Rogers30fab402012-01-23 15:43:46 -0800561 CollectGarbageInternal(clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700562}
563
Ian Rogers30fab402012-01-23 15:43:46 -0800564void Heap::CollectGarbageInternal(bool clear_soft_references) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700565 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700566
Elliott Hughes8d768a92011-09-14 16:35:25 -0700567 ThreadList* thread_list = Runtime::Current()->GetThreadList();
568 thread_list->SuspendAll();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700569
570 size_t initial_size = num_bytes_allocated_;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700571 TimingLogger timings("CollectGarbageInternal");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700572 uint64_t t0 = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700573 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700574 {
575 MarkSweep mark_sweep;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700576 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700577
578 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700579 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700580
581 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700582 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700583
Ian Rogers5d76c432011-10-31 21:42:49 -0700584 mark_sweep.ScanDirtyImageRoots();
585 timings.AddSplit("DirtyImageRoots");
586
587 // Roots are marked on the bitmap and the mark_stack is empty
588 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700589
590 // TODO: if concurrent
591 // unlock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700592 // thread_list->ResumeAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700593
Ian Rogers5d76c432011-10-31 21:42:49 -0700594 // Recursively mark all bits set in the non-image mark bitmap
Carl Shapiro58551df2011-07-24 03:09:51 -0700595 mark_sweep.RecursiveMark();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700596 timings.AddSplit("RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700597
598 // TODO: if concurrent
599 // lock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700600 // thread_list->SuspendAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700601 // re-mark root set
602 // scan dirty objects
603
Ian Rogers30fab402012-01-23 15:43:46 -0800604 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700605 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700606
Elliott Hughes2da50362011-10-10 16:57:08 -0700607 // TODO: if concurrent
608 // swap bitmaps
Carl Shapiro58551df2011-07-24 03:09:51 -0700609
610 mark_sweep.Sweep();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700611 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700612
613 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700614 }
615
616 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700617 timings.AddSplit("GrowForUtilization");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700618 uint64_t t1 = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700619 thread_list->ResumeAll();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700620
621 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800622 RequestHeapTrim();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700623
Ian Rogers3bb17a62012-01-27 23:56:44 -0800624 uint64_t duration_ns = t1 - t0;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800625 bool gc_was_particularly_slow = duration_ns > MsToNs(50); // TODO: crank this down for concurrent.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800626 if (VLOG_IS_ON(gc) || gc_was_particularly_slow) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800627 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
628 size_t bytes_freed = initial_size - num_bytes_allocated_;
629 if (bytes_freed > KB) { // ignore freed bytes in output if > 1KB
630 bytes_freed = RoundDown(bytes_freed, KB);
631 }
632 size_t bytes_allocated = RoundUp(num_bytes_allocated_, KB);
633 // lose low nanoseconds in duration. TODO: make this part of PrettyDuration
634 duration_ns = (duration_ns / 1000) * 1000;
635 size_t total = GetTotalMemory();
636 size_t percentFree = 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
637 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << percentFree << "% free, "
638 << PrettySize(bytes_allocated) << "/" << PrettySize(total) << ", "
639 << "paused " << PrettyDuration(duration_ns);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700640 }
Elliott Hughes767a1472011-10-26 18:49:02 -0700641 Dbg::GcDidFinish();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800642 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700643 timings.Dump();
644 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700645}
646
647void Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700648 lock_->AssertHeld();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700649}
650
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800651void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Ian Rogers30fab402012-01-23 15:43:46 -0800652 size_t alloc_space_capacity = alloc_space_->Capacity();
653 if (max_allowed_footprint > alloc_space_capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800654 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
655 << " to " << PrettySize(alloc_space_capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800656 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700657 }
Ian Rogers30fab402012-01-23 15:43:46 -0800658 alloc_space_->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700659}
660
Ian Rogers3bb17a62012-01-27 23:56:44 -0800661// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700662static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800663// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
664// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700665static const size_t kHeapMinFree = kHeapIdealFree / 4;
666
Carl Shapiro69759ea2011-07-21 18:13:35 -0700667void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700668 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700669
670 // We know what our utilization is at this moment.
671 // This doesn't actually resize any memory. It just lets the heap grow more
672 // when necessary.
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700673 size_t target_size(num_bytes_allocated_ / Heap::GetTargetHeapUtilization());
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700674
675 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
676 target_size = num_bytes_allocated_ + kHeapIdealFree;
677 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
678 target_size = num_bytes_allocated_ + kHeapMinFree;
679 }
680
681 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700682}
683
jeffhaoc1160702011-10-27 15:48:45 -0700684void Heap::ClearGrowthLimit() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800685 ScopedHeapLock heap_lock;
jeffhaoc1160702011-10-27 15:48:45 -0700686 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -0700687 alloc_space_->ClearGrowthLimit();
688}
689
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700690pid_t Heap::GetLockOwner() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700691 return lock_->GetOwner();
692}
693
Elliott Hughes92b3b562011-09-08 16:32:26 -0700694void Heap::Lock() {
Brian Carlstromfad71432011-10-16 20:25:10 -0700695 // Grab the lock, but put ourselves into Thread::kVmWait if it looks
696 // like we're going to have to wait on the mutex. This prevents
697 // deadlock if another thread is calling CollectGarbageInternal,
698 // since they will have the heap lock and be waiting for mutators to
699 // suspend.
700 if (!lock_->TryLock()) {
701 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
702 lock_->Lock();
703 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700704}
705
706void Heap::Unlock() {
707 lock_->Unlock();
708}
709
Elliott Hughesadb460d2011-10-05 17:02:34 -0700710void Heap::SetWellKnownClasses(Class* java_lang_ref_FinalizerReference,
711 Class* java_lang_ref_ReferenceQueue) {
712 java_lang_ref_FinalizerReference_ = java_lang_ref_FinalizerReference;
713 java_lang_ref_ReferenceQueue_ = java_lang_ref_ReferenceQueue;
714 CHECK(java_lang_ref_FinalizerReference_ != NULL);
715 CHECK(java_lang_ref_ReferenceQueue_ != NULL);
716}
717
718void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
719 MemberOffset reference_queue_offset,
720 MemberOffset reference_queueNext_offset,
721 MemberOffset reference_pendingNext_offset,
722 MemberOffset finalizer_reference_zombie_offset) {
723 reference_referent_offset_ = reference_referent_offset;
724 reference_queue_offset_ = reference_queue_offset;
725 reference_queueNext_offset_ = reference_queueNext_offset;
726 reference_pendingNext_offset_ = reference_pendingNext_offset;
727 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
728 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
729 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
730 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
731 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
732 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
733}
734
735Object* Heap::GetReferenceReferent(Object* reference) {
736 DCHECK(reference != NULL);
737 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
738 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
739}
740
741void Heap::ClearReferenceReferent(Object* reference) {
742 DCHECK(reference != NULL);
743 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
744 reference->SetFieldObject(reference_referent_offset_, NULL, true);
745}
746
747// Returns true if the reference object has not yet been enqueued.
748bool Heap::IsEnqueuable(const Object* ref) {
749 DCHECK(ref != NULL);
750 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
751 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
752 return (queue != NULL) && (queue_next == NULL);
753}
754
755void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
756 DCHECK(ref != NULL);
757 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
758 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
759 EnqueuePendingReference(ref, cleared_reference_list);
760}
761
762void Heap::EnqueuePendingReference(Object* ref, Object** list) {
763 DCHECK(ref != NULL);
764 DCHECK(list != NULL);
765
766 if (*list == NULL) {
767 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
768 *list = ref;
769 } else {
770 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
771 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
772 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
773 }
774}
775
776Object* Heap::DequeuePendingReference(Object** list) {
777 DCHECK(list != NULL);
778 DCHECK(*list != NULL);
779 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
780 Object* ref;
781 if (*list == head) {
782 ref = *list;
783 *list = NULL;
784 } else {
785 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
786 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
787 ref = head;
788 }
789 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
790 return ref;
791}
792
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700793void Heap::AddFinalizerReference(Thread* self, Object* object) {
794 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700795 static Method* FinalizerReference_add =
796 java_lang_ref_FinalizerReference_->FindDirectMethod("add", "(Ljava/lang/Object;)V");
797 DCHECK(FinalizerReference_add != NULL);
Elliott Hughes77405792012-03-15 15:22:12 -0700798 JValue args[1];
799 args[0].l = object;
800 FinalizerReference_add->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700801}
802
803void Heap::EnqueueClearedReferences(Object** cleared) {
804 DCHECK(cleared != NULL);
805 if (*cleared != NULL) {
806 static Method* ReferenceQueue_add =
807 java_lang_ref_ReferenceQueue_->FindDirectMethod("add", "(Ljava/lang/ref/Reference;)V");
808 DCHECK(ReferenceQueue_add != NULL);
809
810 Thread* self = Thread::Current();
811 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Elliott Hughes77405792012-03-15 15:22:12 -0700812 JValue args[1];
813 args[0].l = *cleared;
814 ReferenceQueue_add->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700815 *cleared = NULL;
816 }
817}
818
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800819void Heap::RequestHeapTrim() {
820 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
821 // because that only marks object heads, so a large array looks like lots of empty space. We
822 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
823 // to utilization (which is probably inversely proportional to how much benefit we can expect).
824 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
825 // not how much use we're making of those pages.
826 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
827 if (utilization > 0.75f) {
828 // Don't bother trimming the heap if it's more than 75% utilized.
829 // (This percentage was picked arbitrarily.)
830 return;
831 }
Ian Rogerse1d490c2012-02-03 09:09:07 -0800832 if (!Runtime::Current()->IsStarted()) {
833 // Heap trimming isn't supported without a Java runtime (such as at dex2oat time)
834 return;
835 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800836 JNIEnv* env = Thread::Current()->GetJniEnv();
837 static jclass Daemons_class = CacheClass(env, "java/lang/Daemons");
838 static jmethodID Daemons_requestHeapTrim = env->GetStaticMethodID(Daemons_class, "requestHeapTrim", "()V");
839 env->CallStaticVoidMethod(Daemons_class, Daemons_requestHeapTrim);
840 CHECK(!env->ExceptionCheck());
841}
842
Carl Shapiro69759ea2011-07-21 18:13:35 -0700843} // namespace art