blob: 6272bffdc717beb22dddfbc14da0cda3566d9a5e [file] [log] [blame]
Carl Shapiro69759ea2011-07-21 18:13:35 -07001// Copyright 2011 Google Inc. All Rights Reserved.
Carl Shapiro69759ea2011-07-21 18:13:35 -07002
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -07004
Brian Carlstrom58ae9412011-10-04 00:56:06 -07005#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -07006#include <vector>
7
Ian Rogers5d76c432011-10-31 21:42:49 -07008#include "card_table.h"
Elliott Hughes767a1472011-10-26 18:49:02 -07009#include "debugger.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070010#include "image.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070011#include "mark_sweep.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070012#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080013#include "object_utils.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070014#include "space.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070015#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070016#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070017#include "timing_logger.h"
18#include "UniquePtr.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070019
20namespace art {
21
Carl Shapiro58551df2011-07-24 03:09:51 -070022std::vector<Space*> Heap::spaces_;
Carl Shapiro69759ea2011-07-21 18:13:35 -070023
Ian Rogers30fab402012-01-23 15:43:46 -080024AllocSpace* Heap::alloc_space_ = NULL;
jeffhaoc1160702011-10-27 15:48:45 -070025
Carl Shapiro58551df2011-07-24 03:09:51 -070026size_t Heap::num_bytes_allocated_ = 0;
27
28size_t Heap::num_objects_allocated_ = 0;
29
Carl Shapiro69759ea2011-07-21 18:13:35 -070030bool Heap::is_gc_running_ = false;
31
32HeapBitmap* Heap::mark_bitmap_ = NULL;
33
34HeapBitmap* Heap::live_bitmap_ = NULL;
35
Ian Rogers5d76c432011-10-31 21:42:49 -070036CardTable* Heap::card_table_ = NULL;
37
38bool Heap::card_marking_disabled_ = false;
39
Elliott Hughesadb460d2011-10-05 17:02:34 -070040Class* Heap::java_lang_ref_FinalizerReference_ = NULL;
41Class* Heap::java_lang_ref_ReferenceQueue_ = NULL;
42
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070043MemberOffset Heap::reference_referent_offset_ = MemberOffset(0);
44MemberOffset Heap::reference_queue_offset_ = MemberOffset(0);
45MemberOffset Heap::reference_queueNext_offset_ = MemberOffset(0);
46MemberOffset Heap::reference_pendingNext_offset_ = MemberOffset(0);
47MemberOffset Heap::finalizer_reference_zombie_offset_ = MemberOffset(0);
Brian Carlstrom1f870082011-08-23 16:02:11 -070048
Brian Carlstrom395520e2011-09-25 19:35:00 -070049float Heap::target_utilization_ = 0.5;
50
Elliott Hughes92b3b562011-09-08 16:32:26 -070051Mutex* Heap::lock_ = NULL;
52
Elliott Hughes9d5ccec2011-09-19 13:19:50 -070053bool Heap::verify_objects_ = false;
54
Ian Rogers30fab402012-01-23 15:43:46 -080055static void UpdateFirstAndLastSpace(Space** first_space, Space** last_space, Space* space) {
56 if (*first_space == NULL) {
57 *first_space = space;
58 *last_space = space;
59 } else {
60 if ((*first_space)->Begin() > space->Begin()) {
61 *first_space = space;
62 } else if (space->Begin() > (*last_space)->Begin()) {
63 *last_space = space;
64 }
65 }
66}
67
68void Heap::Init(size_t initial_size, size_t growth_limit, size_t capacity,
Brian Carlstrom58ae9412011-10-04 00:56:06 -070069 const std::vector<std::string>& image_file_names) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080070 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -070071 LOG(INFO) << "Heap::Init entering";
72 }
73
Ian Rogers30fab402012-01-23 15:43:46 -080074 // Compute the bounds of all spaces for allocating live and mark bitmaps
75 // there will be at least one space (the alloc space)
76 Space* first_space = NULL;
77 Space* last_space = NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070078
Ian Rogers30fab402012-01-23 15:43:46 -080079 // Requested begin for the alloc space, to follow the mapped image and oat files
80 byte* requested_begin = NULL;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070081 std::vector<Space*> image_spaces;
82 for (size_t i = 0; i < image_file_names.size(); i++) {
Ian Rogers30fab402012-01-23 15:43:46 -080083 ImageSpace* space = Space::CreateImageSpace(image_file_names[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070084 if (space == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -070085 LOG(FATAL) << "Failed to create space from " << image_file_names[i];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070086 }
87 image_spaces.push_back(space);
Ian Rogers30fab402012-01-23 15:43:46 -080088 AddSpace(space);
89 UpdateFirstAndLastSpace(&first_space, &last_space, space);
90 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
91 // isn't going to get in the middle
92 byte* oat_end_addr = space->GetImageHeader().GetOatEnd();
93 CHECK(oat_end_addr > space->End());
94 if (oat_end_addr > requested_begin) {
95 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
96 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -070097 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070098 }
99
Ian Rogers30fab402012-01-23 15:43:46 -0800100 alloc_space_ = Space::CreateAllocSpace("alloc space", initial_size, growth_limit, capacity,
101 requested_begin);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700102 if (alloc_space_ == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700103 LOG(FATAL) << "Failed to create alloc space";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700104 }
Ian Rogers30fab402012-01-23 15:43:46 -0800105 AddSpace(alloc_space_);
106 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
107 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800108 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700109
110 // Allocate the initial live bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800111 UniquePtr<HeapBitmap> live_bitmap(HeapBitmap::Create("dalvik-bitmap-1", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700112 if (live_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700113 LOG(FATAL) << "Failed to create live bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700114 }
115
Ian Rogers30fab402012-01-23 15:43:46 -0800116 // Mark image objects in the live bitmap
117 for (size_t i = 0; i < spaces_.size(); i++) {
118 Space* space = spaces_[i];
119 if (space->IsImageSpace()) {
120 space->AsImageSpace()->RecordImageAllocations(live_bitmap.get());
121 }
122 }
123
Carl Shapiro69759ea2011-07-21 18:13:35 -0700124 // Allocate the initial mark bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800125 UniquePtr<HeapBitmap> mark_bitmap(HeapBitmap::Create("dalvik-bitmap-2", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700126 if (mark_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700127 LOG(FATAL) << "Failed to create mark bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700128 }
129
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800130 // Allocate the card table.
Ian Rogers30fab402012-01-23 15:43:46 -0800131 UniquePtr<CardTable> card_table(CardTable::Create(heap_begin, heap_capacity));
Ian Rogers5d76c432011-10-31 21:42:49 -0700132 if (card_table.get() == NULL) {
133 LOG(FATAL) << "Failed to create card table";
134 }
135
Carl Shapiro69759ea2011-07-21 18:13:35 -0700136 live_bitmap_ = live_bitmap.release();
137 mark_bitmap_ = mark_bitmap.release();
Ian Rogers5d76c432011-10-31 21:42:49 -0700138 card_table_ = card_table.release();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700139
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700140 num_bytes_allocated_ = 0;
141 num_objects_allocated_ = 0;
142
Elliott Hughes92b3b562011-09-08 16:32:26 -0700143 // It's still to early to take a lock because there are no threads yet,
144 // but we can create the heap lock now. We don't create it earlier to
145 // make it clear that you can't use locks during heap initialization.
Elliott Hughes8daa0922011-09-11 13:46:25 -0700146 lock_ = new Mutex("Heap lock");
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700147
Ian Rogers30fab402012-01-23 15:43:46 -0800148 Heap::EnableObjectValidation();
149
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800150 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700151 LOG(INFO) << "Heap::Init exiting";
152 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700153}
154
155void Heap::Destroy() {
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800156 // We can't take the heap lock here because there might be a daemon thread suspended with the
157 // heap lock held. We know though that no non-daemon threads are executing, and we know that
158 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
159 // 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 -0700160 STLDeleteElements(&spaces_);
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800161 delete mark_bitmap_;
162 delete live_bitmap_;
163 delete card_table_;
164 delete lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700165}
166
Elliott Hughes418dfe72011-10-06 18:56:27 -0700167Object* Heap::AllocObject(Class* klass, size_t byte_count) {
168 {
169 ScopedHeapLock lock;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800170 DCHECK(klass == NULL || (klass->IsClassClass() && byte_count >= sizeof(Class)) ||
171 (klass->IsVariableSize() || klass->GetObjectSize() == byte_count) ||
Elliott Hughes91250e02011-12-13 22:30:35 -0800172 strlen(ClassHelper(klass).GetDescriptor()) == 0);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700173 DCHECK_GE(byte_count, sizeof(Object));
174 Object* obj = AllocateLocked(byte_count);
175 if (obj != NULL) {
176 obj->SetClass(klass);
Elliott Hughes545a0642011-11-08 19:10:03 -0800177 if (Dbg::IsAllocTrackingEnabled()) {
178 Dbg::RecordAllocation(klass, byte_count);
179 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700180 return obj;
181 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700182 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700183
184 Thread::Current()->ThrowOutOfMemoryError(klass, byte_count);
185 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700186}
187
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700188bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700189 // Note: we deliberately don't take the lock here, and mustn't test anything that would
190 // require taking the lock.
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700191 if (obj == NULL || !IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700192 return false;
193 }
Ian Rogers30fab402012-01-23 15:43:46 -0800194 for (size_t i = 0; i < spaces_.size(); i++) {
195 if (spaces_[i]->Contains(obj)) {
196 return true;
197 }
198 }
199 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700200}
201
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700202bool Heap::IsLiveObjectLocked(const Object* obj) {
203 lock_->AssertHeld();
204 return IsHeapAddress(obj) && live_bitmap_->Test(obj);
205}
206
Elliott Hughes3e465b12011-09-02 18:26:12 -0700207#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700208void Heap::VerifyObject(const Object* obj) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700209 if (!verify_objects_) {
210 return;
211 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700212 ScopedHeapLock lock;
213 Heap::VerifyObjectLocked(obj);
214}
215#endif
216
217void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700218 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700219 if (obj != NULL) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700220 if (!IsAligned<kObjectAlignment>(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700221 LOG(FATAL) << "Object isn't aligned: " << obj;
222 } else if (!live_bitmap_->Test(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700223 LOG(FATAL) << "Object is dead: " << obj;
224 }
225 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700226 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700227 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
228 Object::ClassOffset().Int32Value();
229 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
230 if (c == NULL) {
Elliott Hughes5d78d392011-12-13 16:53:05 -0800231 LOG(FATAL) << "Null class in object: " << obj;
Elliott Hughes06b37d92011-10-16 11:51:29 -0700232 } else if (!IsAligned<kObjectAlignment>(c)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700233 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
234 } else if (!live_bitmap_->Test(c)) {
235 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
236 }
237 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700238 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700239 // that we don't want to run
Ian Rogers30fab402012-01-23 15:43:46 -0800240 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700241 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
Ian Rogers30fab402012-01-23 15:43:46 -0800242 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700243 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
244 CHECK_EQ(c_c, c_c_c);
245 }
246 }
247}
248
Brian Carlstrom78128a62011-09-15 17:21:19 -0700249void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700250 DCHECK(obj != NULL);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700251 Heap::VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700252}
253
254void Heap::VerifyHeap() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700255 ScopedHeapLock lock;
256 live_bitmap_->Walk(Heap::VerificationCallback, NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700257}
258
Ian Rogers30fab402012-01-23 15:43:46 -0800259void Heap::RecordAllocationLocked(AllocSpace* space, const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700260#ifndef NDEBUG
261 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700262 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700263 }
264#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700265 size_t size = space->AllocationSize(obj);
Elliott Hughes5d78d392011-12-13 16:53:05 -0800266 DCHECK_GT(size, 0u);
Carl Shapiro58551df2011-07-24 03:09:51 -0700267 num_bytes_allocated_ += size;
268 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700269
270 if (Runtime::Current()->HasStatsEnabled()) {
271 RuntimeStats* global_stats = Runtime::Current()->GetStats();
272 RuntimeStats* thread_stats = Thread::Current()->GetStats();
273 ++global_stats->allocated_objects;
274 ++thread_stats->allocated_objects;
275 global_stats->allocated_bytes += size;
276 thread_stats->allocated_bytes += size;
277 }
278
Carl Shapiro58551df2011-07-24 03:09:51 -0700279 live_bitmap_->Set(obj);
280}
281
Elliott Hughes307f75d2011-10-12 18:04:40 -0700282void Heap::RecordFreeLocked(size_t freed_objects, size_t freed_bytes) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700283 lock_->AssertHeld();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700284
285 if (freed_objects < num_objects_allocated_) {
286 num_objects_allocated_ -= freed_objects;
287 } else {
288 num_objects_allocated_ = 0;
289 }
290 if (freed_bytes < num_bytes_allocated_) {
291 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700292 } else {
293 num_bytes_allocated_ = 0;
294 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700295
296 if (Runtime::Current()->HasStatsEnabled()) {
297 RuntimeStats* global_stats = Runtime::Current()->GetStats();
298 RuntimeStats* thread_stats = Thread::Current()->GetStats();
299 ++global_stats->freed_objects;
300 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700301 global_stats->freed_bytes += freed_bytes;
302 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700303 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700304}
305
Elliott Hughes92b3b562011-09-08 16:32:26 -0700306Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700307 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700308 DCHECK(alloc_space_ != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800309 AllocSpace* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700310 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700311 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700312 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700313 }
314 return obj;
315}
316
Ian Rogers30fab402012-01-23 15:43:46 -0800317Object* Heap::AllocateLocked(AllocSpace* space, size_t alloc_size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700318 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700319
Brian Carlstromb82b6872011-10-26 17:18:07 -0700320 // Since allocation can cause a GC which will need to SuspendAll,
321 // make sure all allocators are in the kRunnable state.
322 DCHECK_EQ(Thread::Current()->GetState(), Thread::kRunnable);
323
Ian Rogers30fab402012-01-23 15:43:46 -0800324 // Fail impossible allocations
325 if (alloc_size > space->Capacity()) {
326 // On failure collect soft references
327 CollectGarbageInternal(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700328 return NULL;
329 }
330
Ian Rogers30fab402012-01-23 15:43:46 -0800331 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700332 if (ptr != NULL) {
333 return ptr;
334 }
335
Ian Rogers30fab402012-01-23 15:43:46 -0800336 // The allocation failed. If the GC is running, block until it completes and retry.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700337 if (is_gc_running_) {
Ian Rogers30fab402012-01-23 15:43:46 -0800338 // The GC is concurrently tracing the heap. Release the heap lock, wait for the GC to
339 // complete, and retrying allocating.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700340 WaitForConcurrentGcToComplete();
Ian Rogers30fab402012-01-23 15:43:46 -0800341 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700342 if (ptr != NULL) {
343 return ptr;
344 }
345 }
346
347 // Another failure. Our thread was starved or there may be too many
348 // live objects. Try a foreground GC. This will have no effect if
349 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700350 if (Runtime::Current()->HasStatsEnabled()) {
351 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
352 ++Thread::Current()->GetStats()->gc_for_alloc_count;
353 }
Ian Rogers30fab402012-01-23 15:43:46 -0800354 CollectGarbageInternal(false);
355 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700356 if (ptr != NULL) {
357 return ptr;
358 }
359
360 // Even that didn't work; this is an exceptional state.
361 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800362 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700363 if (ptr != NULL) {
364 //size_t new_footprint = dvmHeapSourceGetIdealFootprint();
Ian Rogers30fab402012-01-23 15:43:46 -0800365 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700366 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700367 // free space is equal to the old free space + the
368 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800369 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
370 << "for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700371 return ptr;
372 }
373
374 // Most allocations should have succeeded by now, so the heap is
375 // really full, really fragmented, or the requested size is really
376 // big. Do another GC, collecting SoftReferences this time. The VM
377 // spec requires that all SoftReferences have been collected and
378 // cleared before throwing an OOME.
379
Elliott Hughes418dfe72011-10-06 18:56:27 -0700380 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800381 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Ian Rogers30fab402012-01-23 15:43:46 -0800382 CollectGarbageInternal(true);
383 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700384 if (ptr != NULL) {
385 return ptr;
386 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700387
Ian Rogers3bb17a62012-01-27 23:56:44 -0800388 LOG(ERROR) << "Out of memory on a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700389
Carl Shapiro58551df2011-07-24 03:09:51 -0700390 // TODO: tell the HeapSource to dump its state
391 // TODO: dump stack traces for all threads
Carl Shapiro69759ea2011-07-21 18:13:35 -0700392
Carl Shapiro69759ea2011-07-21 18:13:35 -0700393 return NULL;
394}
395
Elliott Hughesbf86d042011-08-31 17:53:14 -0700396int64_t Heap::GetMaxMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800397 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700398}
399
400int64_t Heap::GetTotalMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800401 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700402}
403
404int64_t Heap::GetFreeMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800405 return alloc_space_->Capacity() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700406}
407
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700408class InstanceCounter {
409 public:
410 InstanceCounter(Class* c, bool count_assignable)
411 : class_(c), count_assignable_(count_assignable), count_(0) {
412 }
413
414 size_t GetCount() {
415 return count_;
416 }
417
418 static void Callback(Object* o, void* arg) {
419 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
420 }
421
422 private:
423 void VisitInstance(Object* o) {
424 Class* instance_class = o->GetClass();
425 if (count_assignable_) {
426 if (instance_class == class_) {
427 ++count_;
428 }
429 } else {
430 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
431 ++count_;
432 }
433 }
434 }
435
436 Class* class_;
437 bool count_assignable_;
438 size_t count_;
439};
440
441int64_t Heap::CountInstances(Class* c, bool count_assignable) {
442 ScopedHeapLock lock;
443 InstanceCounter counter(c, count_assignable);
444 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
445 return counter.GetCount();
446}
447
Ian Rogers30fab402012-01-23 15:43:46 -0800448void Heap::CollectGarbage(bool clear_soft_references) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700449 ScopedHeapLock lock;
Ian Rogers30fab402012-01-23 15:43:46 -0800450 CollectGarbageInternal(clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700451}
452
Ian Rogers30fab402012-01-23 15:43:46 -0800453void Heap::CollectGarbageInternal(bool clear_soft_references) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700454 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700455
Elliott Hughes8d768a92011-09-14 16:35:25 -0700456 ThreadList* thread_list = Runtime::Current()->GetThreadList();
457 thread_list->SuspendAll();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700458
459 size_t initial_size = num_bytes_allocated_;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700460 TimingLogger timings("CollectGarbageInternal");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700461 uint64_t t0 = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700462 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700463 {
464 MarkSweep mark_sweep;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700465 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700466
467 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700468 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700469
470 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700471 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700472
Ian Rogers5d76c432011-10-31 21:42:49 -0700473 mark_sweep.ScanDirtyImageRoots();
474 timings.AddSplit("DirtyImageRoots");
475
476 // Roots are marked on the bitmap and the mark_stack is empty
477 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700478
479 // TODO: if concurrent
480 // unlock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700481 // thread_list->ResumeAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700482
Ian Rogers5d76c432011-10-31 21:42:49 -0700483 // Recursively mark all bits set in the non-image mark bitmap
Carl Shapiro58551df2011-07-24 03:09:51 -0700484 mark_sweep.RecursiveMark();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700485 timings.AddSplit("RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700486
487 // TODO: if concurrent
488 // lock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700489 // thread_list->SuspendAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700490 // re-mark root set
491 // scan dirty objects
492
Ian Rogers30fab402012-01-23 15:43:46 -0800493 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700494 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700495
Elliott Hughes2da50362011-10-10 16:57:08 -0700496 // TODO: if concurrent
497 // swap bitmaps
Carl Shapiro58551df2011-07-24 03:09:51 -0700498
499 mark_sweep.Sweep();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700500 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700501
502 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700503 }
504
505 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700506 timings.AddSplit("GrowForUtilization");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700507 uint64_t t1 = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700508 thread_list->ResumeAll();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700509
510 EnqueueClearedReferences(&cleared_references);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700511
Ian Rogers3bb17a62012-01-27 23:56:44 -0800512 uint64_t duration_ns = t1 - t0;
513 bool gc_was_particularly_slow = duration_ns > MsToNs(100); // TODO: crank this down for concurrent.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800514 if (VLOG_IS_ON(gc) || gc_was_particularly_slow) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800515 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
516 size_t bytes_freed = initial_size - num_bytes_allocated_;
517 if (bytes_freed > KB) { // ignore freed bytes in output if > 1KB
518 bytes_freed = RoundDown(bytes_freed, KB);
519 }
520 size_t bytes_allocated = RoundUp(num_bytes_allocated_, KB);
521 // lose low nanoseconds in duration. TODO: make this part of PrettyDuration
522 duration_ns = (duration_ns / 1000) * 1000;
523 size_t total = GetTotalMemory();
524 size_t percentFree = 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
525 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << percentFree << "% free, "
526 << PrettySize(bytes_allocated) << "/" << PrettySize(total) << ", "
527 << "paused " << PrettyDuration(duration_ns);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700528 }
Elliott Hughes767a1472011-10-26 18:49:02 -0700529 Dbg::GcDidFinish();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800530 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700531 timings.Dump();
532 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700533}
534
535void Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700536 lock_->AssertHeld();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700537}
538
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800539void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Ian Rogers30fab402012-01-23 15:43:46 -0800540 size_t alloc_space_capacity = alloc_space_->Capacity();
541 if (max_allowed_footprint > alloc_space_capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800542 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
543 << " to " << PrettySize(alloc_space_capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800544 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700545 }
Ian Rogers30fab402012-01-23 15:43:46 -0800546 alloc_space_->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700547}
548
Ian Rogers3bb17a62012-01-27 23:56:44 -0800549// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700550static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800551// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
552// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700553static const size_t kHeapMinFree = kHeapIdealFree / 4;
554
Carl Shapiro69759ea2011-07-21 18:13:35 -0700555void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700556 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700557
558 // We know what our utilization is at this moment.
559 // This doesn't actually resize any memory. It just lets the heap grow more
560 // when necessary.
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700561 size_t target_size(num_bytes_allocated_ / Heap::GetTargetHeapUtilization());
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700562
563 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
564 target_size = num_bytes_allocated_ + kHeapIdealFree;
565 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
566 target_size = num_bytes_allocated_ + kHeapMinFree;
567 }
568
569 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700570}
571
jeffhaoc1160702011-10-27 15:48:45 -0700572void Heap::ClearGrowthLimit() {
573 ScopedHeapLock lock;
574 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -0700575 alloc_space_->ClearGrowthLimit();
576}
577
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700578pid_t Heap::GetLockOwner() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700579 return lock_->GetOwner();
580}
581
Elliott Hughes92b3b562011-09-08 16:32:26 -0700582void Heap::Lock() {
Brian Carlstromfad71432011-10-16 20:25:10 -0700583 // Grab the lock, but put ourselves into Thread::kVmWait if it looks
584 // like we're going to have to wait on the mutex. This prevents
585 // deadlock if another thread is calling CollectGarbageInternal,
586 // since they will have the heap lock and be waiting for mutators to
587 // suspend.
588 if (!lock_->TryLock()) {
589 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
590 lock_->Lock();
591 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700592}
593
594void Heap::Unlock() {
595 lock_->Unlock();
596}
597
Elliott Hughesadb460d2011-10-05 17:02:34 -0700598void Heap::SetWellKnownClasses(Class* java_lang_ref_FinalizerReference,
599 Class* java_lang_ref_ReferenceQueue) {
600 java_lang_ref_FinalizerReference_ = java_lang_ref_FinalizerReference;
601 java_lang_ref_ReferenceQueue_ = java_lang_ref_ReferenceQueue;
602 CHECK(java_lang_ref_FinalizerReference_ != NULL);
603 CHECK(java_lang_ref_ReferenceQueue_ != NULL);
604}
605
606void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
607 MemberOffset reference_queue_offset,
608 MemberOffset reference_queueNext_offset,
609 MemberOffset reference_pendingNext_offset,
610 MemberOffset finalizer_reference_zombie_offset) {
611 reference_referent_offset_ = reference_referent_offset;
612 reference_queue_offset_ = reference_queue_offset;
613 reference_queueNext_offset_ = reference_queueNext_offset;
614 reference_pendingNext_offset_ = reference_pendingNext_offset;
615 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
616 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
617 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
618 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
619 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
620 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
621}
622
623Object* Heap::GetReferenceReferent(Object* reference) {
624 DCHECK(reference != NULL);
625 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
626 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
627}
628
629void Heap::ClearReferenceReferent(Object* reference) {
630 DCHECK(reference != NULL);
631 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
632 reference->SetFieldObject(reference_referent_offset_, NULL, true);
633}
634
635// Returns true if the reference object has not yet been enqueued.
636bool Heap::IsEnqueuable(const Object* ref) {
637 DCHECK(ref != NULL);
638 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
639 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
640 return (queue != NULL) && (queue_next == NULL);
641}
642
643void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
644 DCHECK(ref != NULL);
645 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
646 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
647 EnqueuePendingReference(ref, cleared_reference_list);
648}
649
650void Heap::EnqueuePendingReference(Object* ref, Object** list) {
651 DCHECK(ref != NULL);
652 DCHECK(list != NULL);
653
654 if (*list == NULL) {
655 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
656 *list = ref;
657 } else {
658 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
659 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
660 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
661 }
662}
663
664Object* Heap::DequeuePendingReference(Object** list) {
665 DCHECK(list != NULL);
666 DCHECK(*list != NULL);
667 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
668 Object* ref;
669 if (*list == head) {
670 ref = *list;
671 *list = NULL;
672 } else {
673 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
674 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
675 ref = head;
676 }
677 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
678 return ref;
679}
680
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700681void Heap::AddFinalizerReference(Thread* self, Object* object) {
682 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700683 static Method* FinalizerReference_add =
684 java_lang_ref_FinalizerReference_->FindDirectMethod("add", "(Ljava/lang/Object;)V");
685 DCHECK(FinalizerReference_add != NULL);
686 Object* args[] = { object };
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700687 FinalizerReference_add->Invoke(self, NULL, reinterpret_cast<byte*>(&args), NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700688}
689
690void Heap::EnqueueClearedReferences(Object** cleared) {
691 DCHECK(cleared != NULL);
692 if (*cleared != NULL) {
693 static Method* ReferenceQueue_add =
694 java_lang_ref_ReferenceQueue_->FindDirectMethod("add", "(Ljava/lang/ref/Reference;)V");
695 DCHECK(ReferenceQueue_add != NULL);
696
697 Thread* self = Thread::Current();
698 ScopedThreadStateChange tsc(self, Thread::kRunnable);
699 Object* args[] = { *cleared };
700 ReferenceQueue_add->Invoke(self, NULL, reinterpret_cast<byte*>(&args), NULL);
701 *cleared = NULL;
702 }
703}
704
Carl Shapiro69759ea2011-07-21 18:13:35 -0700705} // namespace art