blob: eb4f3e8cef9914fdfa062c7df5559d0c6f7aa9a9 [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
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700242 mark_stack_ = MarkStack::Create();
243
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800244 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700245 // but we can create the heap lock now. We don't create it earlier to
246 // make it clear that you can't use locks during heap initialization.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800247 lock_ = new Mutex("Heap lock", kHeapLock);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700248
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800249 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800250 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700251 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700252}
253
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800254void Heap::AddSpace(Space* space) {
255 spaces_.push_back(space);
256}
257
258Heap::~Heap() {
259 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800260 // We can't take the heap lock here because there might be a daemon thread suspended with the
261 // heap lock held. We know though that no non-daemon threads are executing, and we know that
262 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
263 // 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 -0700264 STLDeleteElements(&spaces_);
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800265 delete mark_bitmap_;
266 delete live_bitmap_;
267 delete card_table_;
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700268 delete mark_stack_;
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800269 delete lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700270}
271
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700272static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
273 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
274
275 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
276 size_t chunk_free_bytes = 0;
277 if (used_bytes < chunk_size) {
278 chunk_free_bytes = chunk_size - used_bytes;
279 }
280
281 if (chunk_free_bytes > max_contiguous_allocation) {
282 max_contiguous_allocation = chunk_free_bytes;
283 }
284}
285
286Object* Heap::AllocObject(Class* c, size_t byte_count) {
287 // Used in the detail message if we throw an OOME.
288 int64_t total_bytes_free;
289 size_t max_contiguous_allocation;
290
Elliott Hughes418dfe72011-10-06 18:56:27 -0700291 {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800292 ScopedHeapLock heap_lock;
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700293 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
294 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
295 strlen(ClassHelper(c).GetDescriptor()) == 0);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700296 DCHECK_GE(byte_count, sizeof(Object));
297 Object* obj = AllocateLocked(byte_count);
298 if (obj != NULL) {
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700299 obj->SetClass(c);
Elliott Hughes545a0642011-11-08 19:10:03 -0800300 if (Dbg::IsAllocTrackingEnabled()) {
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700301 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes545a0642011-11-08 19:10:03 -0800302 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700303 return obj;
304 }
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700305 total_bytes_free = GetFreeMemory();
306 max_contiguous_allocation = 0;
307 GetAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Carl Shapiro58551df2011-07-24 03:09:51 -0700308 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700309
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700310 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
311 byte_count,
312 PrettyDescriptor(c).c_str(),
313 total_bytes_free, max_contiguous_allocation));
314 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700315 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700316}
317
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700318bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700319 // Note: we deliberately don't take the lock here, and mustn't test anything that would
320 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700321 if (obj == NULL) {
322 return true;
323 }
324 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700325 return false;
326 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800327 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800328 if (spaces_[i]->Contains(obj)) {
329 return true;
330 }
331 }
332 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700333}
334
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700335bool Heap::IsLiveObjectLocked(const Object* obj) {
336 lock_->AssertHeld();
337 return IsHeapAddress(obj) && live_bitmap_->Test(obj);
338}
339
Elliott Hughes3e465b12011-09-02 18:26:12 -0700340#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700341void Heap::VerifyObject(const Object* obj) {
jeffhao25045522012-03-13 19:34:37 -0700342 if (this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700343 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700344 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700345 return;
346 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800347 ScopedHeapLock heap_lock;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700348 Heap::VerifyObjectLocked(obj);
349}
350#endif
351
352void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700353 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700354 if (obj != NULL) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700355 if (!IsAligned<kObjectAlignment>(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356 LOG(FATAL) << "Object isn't aligned: " << obj;
357 } else if (!live_bitmap_->Test(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358 LOG(FATAL) << "Object is dead: " << obj;
359 }
360 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700361 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700362 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
363 Object::ClassOffset().Int32Value();
364 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
365 if (c == NULL) {
Elliott Hughes5d78d392011-12-13 16:53:05 -0800366 LOG(FATAL) << "Null class in object: " << obj;
Elliott Hughes06b37d92011-10-16 11:51:29 -0700367 } else if (!IsAligned<kObjectAlignment>(c)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
369 } else if (!live_bitmap_->Test(c)) {
370 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
371 }
372 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700373 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374 // that we don't want to run
Ian Rogers30fab402012-01-23 15:43:46 -0800375 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700376 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
Ian Rogers30fab402012-01-23 15:43:46 -0800377 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
379 CHECK_EQ(c_c, c_c_c);
380 }
381 }
382}
383
Brian Carlstrom78128a62011-09-15 17:21:19 -0700384void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700385 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800386 reinterpret_cast<Heap*>(arg)->VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700387}
388
389void Heap::VerifyHeap() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800390 ScopedHeapLock heap_lock;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800391 live_bitmap_->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392}
393
Ian Rogers30fab402012-01-23 15:43:46 -0800394void Heap::RecordAllocationLocked(AllocSpace* space, const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700395#ifndef NDEBUG
396 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700397 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700398 }
399#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700400 size_t size = space->AllocationSize(obj);
Elliott Hughes5d78d392011-12-13 16:53:05 -0800401 DCHECK_GT(size, 0u);
Carl Shapiro58551df2011-07-24 03:09:51 -0700402 num_bytes_allocated_ += size;
403 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700404
405 if (Runtime::Current()->HasStatsEnabled()) {
406 RuntimeStats* global_stats = Runtime::Current()->GetStats();
407 RuntimeStats* thread_stats = Thread::Current()->GetStats();
408 ++global_stats->allocated_objects;
409 ++thread_stats->allocated_objects;
410 global_stats->allocated_bytes += size;
411 thread_stats->allocated_bytes += size;
412 }
413
Carl Shapiro58551df2011-07-24 03:09:51 -0700414 live_bitmap_->Set(obj);
415}
416
Elliott Hughes307f75d2011-10-12 18:04:40 -0700417void Heap::RecordFreeLocked(size_t freed_objects, size_t freed_bytes) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700418 lock_->AssertHeld();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700419
420 if (freed_objects < num_objects_allocated_) {
421 num_objects_allocated_ -= freed_objects;
422 } else {
423 num_objects_allocated_ = 0;
424 }
425 if (freed_bytes < num_bytes_allocated_) {
426 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700427 } else {
428 num_bytes_allocated_ = 0;
429 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700430
431 if (Runtime::Current()->HasStatsEnabled()) {
432 RuntimeStats* global_stats = Runtime::Current()->GetStats();
433 RuntimeStats* thread_stats = Thread::Current()->GetStats();
434 ++global_stats->freed_objects;
435 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700436 global_stats->freed_bytes += freed_bytes;
437 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700438 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700439}
440
Elliott Hughes92b3b562011-09-08 16:32:26 -0700441Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700442 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700443 DCHECK(alloc_space_ != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800444 AllocSpace* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700445 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700446 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700447 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700448 }
449 return obj;
450}
451
Ian Rogers30fab402012-01-23 15:43:46 -0800452Object* Heap::AllocateLocked(AllocSpace* space, size_t alloc_size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700453 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700454
Brian Carlstromb82b6872011-10-26 17:18:07 -0700455 // Since allocation can cause a GC which will need to SuspendAll,
456 // make sure all allocators are in the kRunnable state.
Elliott Hughes34e06962012-04-09 13:55:55 -0700457 CHECK_EQ(Thread::Current()->GetState(), kRunnable);
Brian Carlstromb82b6872011-10-26 17:18:07 -0700458
Ian Rogers30fab402012-01-23 15:43:46 -0800459 // Fail impossible allocations
460 if (alloc_size > space->Capacity()) {
461 // On failure collect soft references
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700462 CollectGarbageInternal(false, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700463 return NULL;
464 }
465
Ian Rogers30fab402012-01-23 15:43:46 -0800466 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700467 if (ptr != NULL) {
468 return ptr;
469 }
470
Ian Rogers30fab402012-01-23 15:43:46 -0800471 // The allocation failed. If the GC is running, block until it completes and retry.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700472 if (is_gc_running_) {
Ian Rogers30fab402012-01-23 15:43:46 -0800473 // The GC is concurrently tracing the heap. Release the heap lock, wait for the GC to
474 // complete, and retrying allocating.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700475 WaitForConcurrentGcToComplete();
Ian Rogers30fab402012-01-23 15:43:46 -0800476 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700477 if (ptr != NULL) {
478 return ptr;
479 }
480 }
481
482 // Another failure. Our thread was starved or there may be too many
483 // live objects. Try a foreground GC. This will have no effect if
484 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700485 if (Runtime::Current()->HasStatsEnabled()) {
486 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
487 ++Thread::Current()->GetStats()->gc_for_alloc_count;
488 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700489 CollectGarbageInternal(false, false);
Ian Rogers30fab402012-01-23 15:43:46 -0800490 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700491 if (ptr != NULL) {
492 return ptr;
493 }
494
495 // Even that didn't work; this is an exceptional state.
496 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800497 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700498 if (ptr != NULL) {
499 //size_t new_footprint = dvmHeapSourceGetIdealFootprint();
Ian Rogers30fab402012-01-23 15:43:46 -0800500 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700501 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700502 // free space is equal to the old free space + the
503 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800504 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800505 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700506 return ptr;
507 }
508
Elliott Hughes81ff3182012-03-23 20:35:56 -0700509 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
510 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
511 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700512
Elliott Hughes418dfe72011-10-06 18:56:27 -0700513 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800514 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700515 CollectGarbageInternal(false, true);
Ian Rogers30fab402012-01-23 15:43:46 -0800516 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700517 if (ptr != NULL) {
518 return ptr;
519 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700520
Carl Shapiro69759ea2011-07-21 18:13:35 -0700521 return NULL;
522}
523
Elliott Hughesbf86d042011-08-31 17:53:14 -0700524int64_t Heap::GetMaxMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800525 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700526}
527
528int64_t Heap::GetTotalMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800529 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700530}
531
532int64_t Heap::GetFreeMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800533 return alloc_space_->Capacity() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700534}
535
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700536class InstanceCounter {
537 public:
538 InstanceCounter(Class* c, bool count_assignable)
539 : class_(c), count_assignable_(count_assignable), count_(0) {
540 }
541
542 size_t GetCount() {
543 return count_;
544 }
545
546 static void Callback(Object* o, void* arg) {
547 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
548 }
549
550 private:
551 void VisitInstance(Object* o) {
552 Class* instance_class = o->GetClass();
553 if (count_assignable_) {
554 if (instance_class == class_) {
555 ++count_;
556 }
557 } else {
558 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
559 ++count_;
560 }
561 }
562 }
563
564 Class* class_;
565 bool count_assignable_;
566 size_t count_;
567};
568
569int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800570 ScopedHeapLock heap_lock;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700571 InstanceCounter counter(c, count_assignable);
572 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
573 return counter.GetCount();
574}
575
Ian Rogers30fab402012-01-23 15:43:46 -0800576void Heap::CollectGarbage(bool clear_soft_references) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800577 ScopedHeapLock heap_lock;
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700578 CollectGarbageInternal(false, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700579}
580
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700581void Heap::CollectGarbageInternal(bool concurrent, bool clear_soft_references) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700582 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700583
Elliott Hughes8d768a92011-09-14 16:35:25 -0700584 ThreadList* thread_list = Runtime::Current()->GetThreadList();
585 thread_list->SuspendAll();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700586
587 size_t initial_size = num_bytes_allocated_;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700588 TimingLogger timings("CollectGarbageInternal");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700589 uint64_t t0 = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700590 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700591 {
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700592 MarkSweep mark_sweep(mark_stack_);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700593 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700594
595 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700596 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700597
598 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700599 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700600
Ian Rogers5d76c432011-10-31 21:42:49 -0700601 // 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
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700604 if (concurrent) {
605 Unlock();
606 thread_list->ResumeAll();
607 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700608
Ian Rogers5d76c432011-10-31 21:42:49 -0700609 // Recursively mark all bits set in the non-image mark bitmap
Carl Shapiro58551df2011-07-24 03:09:51 -0700610 mark_sweep.RecursiveMark();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700611 timings.AddSplit("RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700612
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700613 if (concurrent) {
614 Lock();
615 thread_list->SuspendAll();
616
617 // Re-mark root set.
618 mark_sweep.ReMarkRoots();
619 timings.AddSplit("ReMarkRoots");
620 }
621
622 // Scan dirty objects, this is required even if we are not doing a
623 // concurrent GC since we use the card table to locate image roots.
624 mark_sweep.RecursiveMarkDirtyObjects();
625 timings.AddSplit("RecursiveMarkDirtyObjects");
Carl Shapiro58551df2011-07-24 03:09:51 -0700626
Ian Rogers30fab402012-01-23 15:43:46 -0800627 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700628 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700629
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700630 // TODO: swap live and marked bitmaps
631 // Note: Need to be careful about image spaces if we do this since not
632 // everything image space will be marked, resulting in things not being
633 // marked as live anymore.
634
635 // Verify that we only reach marked objects from the image space
636 mark_sweep.VerifyImageRoots();
637 timings.AddSplit("VerifyImageRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700638
639 mark_sweep.Sweep();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700640 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700641
642 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700643 }
644
645 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700646 timings.AddSplit("GrowForUtilization");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700647 uint64_t t1 = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700648 thread_list->ResumeAll();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700649
650 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800651 RequestHeapTrim();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700652
Ian Rogers3bb17a62012-01-27 23:56:44 -0800653 uint64_t duration_ns = t1 - t0;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800654 bool gc_was_particularly_slow = duration_ns > MsToNs(50); // TODO: crank this down for concurrent.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800655 if (VLOG_IS_ON(gc) || gc_was_particularly_slow) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800656 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
657 size_t bytes_freed = initial_size - num_bytes_allocated_;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800658 // lose low nanoseconds in duration. TODO: make this part of PrettyDuration
659 duration_ns = (duration_ns / 1000) * 1000;
Elliott Hughesc967f782012-04-16 10:23:15 -0700660 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
661 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
Ian Rogers3bb17a62012-01-27 23:56:44 -0800662 << "paused " << PrettyDuration(duration_ns);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700663 }
Elliott Hughes767a1472011-10-26 18:49:02 -0700664 Dbg::GcDidFinish();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800665 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700666 timings.Dump();
667 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700668}
669
670void Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700671 lock_->AssertHeld();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700672}
673
Elliott Hughesc967f782012-04-16 10:23:15 -0700674void Heap::DumpForSigQuit(std::ostream& os) {
675 os << "Heap: " << GetPercentFree() << "% free, "
676 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory())
Elliott Hughesae80b492012-04-24 10:43:17 -0700677 << "; " << num_objects_allocated_ << " objects\n";
Elliott Hughesc967f782012-04-16 10:23:15 -0700678}
679
680size_t Heap::GetPercentFree() {
681 size_t total = GetTotalMemory();
682 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
683}
684
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800685void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Ian Rogers30fab402012-01-23 15:43:46 -0800686 size_t alloc_space_capacity = alloc_space_->Capacity();
687 if (max_allowed_footprint > alloc_space_capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800688 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
689 << " to " << PrettySize(alloc_space_capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800690 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700691 }
Ian Rogers30fab402012-01-23 15:43:46 -0800692 alloc_space_->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700693}
694
Ian Rogers3bb17a62012-01-27 23:56:44 -0800695// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700696static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800697// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
698// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700699static const size_t kHeapMinFree = kHeapIdealFree / 4;
700
Carl Shapiro69759ea2011-07-21 18:13:35 -0700701void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700702 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700703
704 // We know what our utilization is at this moment.
705 // This doesn't actually resize any memory. It just lets the heap grow more
706 // when necessary.
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700707 size_t target_size(num_bytes_allocated_ / Heap::GetTargetHeapUtilization());
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700708
709 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
710 target_size = num_bytes_allocated_ + kHeapIdealFree;
711 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
712 target_size = num_bytes_allocated_ + kHeapMinFree;
713 }
714
715 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700716}
717
jeffhaoc1160702011-10-27 15:48:45 -0700718void Heap::ClearGrowthLimit() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800719 ScopedHeapLock heap_lock;
jeffhaoc1160702011-10-27 15:48:45 -0700720 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -0700721 alloc_space_->ClearGrowthLimit();
722}
723
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700724pid_t Heap::GetLockOwner() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700725 return lock_->GetOwner();
726}
727
Elliott Hughes92b3b562011-09-08 16:32:26 -0700728void Heap::Lock() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700729 // Grab the lock, but put ourselves into kVmWait if it looks
Brian Carlstromfad71432011-10-16 20:25:10 -0700730 // like we're going to have to wait on the mutex. This prevents
731 // deadlock if another thread is calling CollectGarbageInternal,
732 // since they will have the heap lock and be waiting for mutators to
733 // suspend.
734 if (!lock_->TryLock()) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700735 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Brian Carlstromfad71432011-10-16 20:25:10 -0700736 lock_->Lock();
737 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700738}
739
740void Heap::Unlock() {
741 lock_->Unlock();
742}
743
Elliott Hughesadb460d2011-10-05 17:02:34 -0700744void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
745 MemberOffset reference_queue_offset,
746 MemberOffset reference_queueNext_offset,
747 MemberOffset reference_pendingNext_offset,
748 MemberOffset finalizer_reference_zombie_offset) {
749 reference_referent_offset_ = reference_referent_offset;
750 reference_queue_offset_ = reference_queue_offset;
751 reference_queueNext_offset_ = reference_queueNext_offset;
752 reference_pendingNext_offset_ = reference_pendingNext_offset;
753 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
754 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
755 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
756 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
757 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
758 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
759}
760
761Object* Heap::GetReferenceReferent(Object* reference) {
762 DCHECK(reference != NULL);
763 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
764 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
765}
766
767void Heap::ClearReferenceReferent(Object* reference) {
768 DCHECK(reference != NULL);
769 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
770 reference->SetFieldObject(reference_referent_offset_, NULL, true);
771}
772
773// Returns true if the reference object has not yet been enqueued.
774bool Heap::IsEnqueuable(const Object* ref) {
775 DCHECK(ref != NULL);
776 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
777 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
778 return (queue != NULL) && (queue_next == NULL);
779}
780
781void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
782 DCHECK(ref != NULL);
783 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
784 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
785 EnqueuePendingReference(ref, cleared_reference_list);
786}
787
788void Heap::EnqueuePendingReference(Object* ref, Object** list) {
789 DCHECK(ref != NULL);
790 DCHECK(list != NULL);
791
792 if (*list == NULL) {
793 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
794 *list = ref;
795 } else {
796 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
797 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
798 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
799 }
800}
801
802Object* Heap::DequeuePendingReference(Object** list) {
803 DCHECK(list != NULL);
804 DCHECK(*list != NULL);
805 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
806 Object* ref;
807 if (*list == head) {
808 ref = *list;
809 *list = NULL;
810 } else {
811 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
812 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
813 ref = head;
814 }
815 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
816 return ref;
817}
818
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700819void Heap::AddFinalizerReference(Thread* self, Object* object) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700820 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughes77405792012-03-15 15:22:12 -0700821 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700822 args[0].SetL(object);
Elliott Hughesa4f94742012-05-29 16:28:38 -0700823 DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700824}
825
826void Heap::EnqueueClearedReferences(Object** cleared) {
827 DCHECK(cleared != NULL);
828 if (*cleared != NULL) {
Elliott Hughesadb460d2011-10-05 17:02:34 -0700829 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -0700830 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughes77405792012-03-15 15:22:12 -0700831 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700832 args[0].SetL(*cleared);
Elliott Hughesa4f94742012-05-29 16:28:38 -0700833 DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700834 *cleared = NULL;
835 }
836}
837
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800838void Heap::RequestHeapTrim() {
839 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
840 // because that only marks object heads, so a large array looks like lots of empty space. We
841 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
842 // to utilization (which is probably inversely proportional to how much benefit we can expect).
843 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
844 // not how much use we're making of those pages.
845 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
846 if (utilization > 0.75f) {
847 // Don't bother trimming the heap if it's more than 75% utilized.
848 // (This percentage was picked arbitrarily.)
849 return;
850 }
Ian Rogerse1d490c2012-02-03 09:09:07 -0800851 if (!Runtime::Current()->IsStarted()) {
852 // Heap trimming isn't supported without a Java runtime (such as at dex2oat time)
853 return;
854 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800855 JNIEnv* env = Thread::Current()->GetJniEnv();
Elliott Hugheseac76672012-05-24 21:56:51 -0700856 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800857 CHECK(!env->ExceptionCheck());
858}
859
Carl Shapiro69759ea2011-07-21 18:13:35 -0700860} // namespace art