blob: 019cfe2b4daf6cb8f32edcea6e0ab51d0b11bbff [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
Elliott Hughes90a33692011-08-30 13:27:07 -07008#include "UniquePtr.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07009#include "image.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070010#include "mark_sweep.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070011#include "object.h"
12#include "space.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070013#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070014#include "thread_list.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070015
16namespace art {
17
Carl Shapiro58551df2011-07-24 03:09:51 -070018std::vector<Space*> Heap::spaces_;
Carl Shapiro69759ea2011-07-21 18:13:35 -070019
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070020Space* Heap::alloc_space_ = NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -070021
22size_t Heap::maximum_size_ = 0;
23
Carl Shapiro58551df2011-07-24 03:09:51 -070024size_t Heap::num_bytes_allocated_ = 0;
25
26size_t Heap::num_objects_allocated_ = 0;
27
Carl Shapiro69759ea2011-07-21 18:13:35 -070028bool Heap::is_gc_running_ = false;
29
30HeapBitmap* Heap::mark_bitmap_ = NULL;
31
32HeapBitmap* Heap::live_bitmap_ = NULL;
33
Elliott Hughesadb460d2011-10-05 17:02:34 -070034Class* Heap::java_lang_ref_FinalizerReference_ = NULL;
35Class* Heap::java_lang_ref_ReferenceQueue_ = NULL;
36
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070037MemberOffset Heap::reference_referent_offset_ = MemberOffset(0);
38MemberOffset Heap::reference_queue_offset_ = MemberOffset(0);
39MemberOffset Heap::reference_queueNext_offset_ = MemberOffset(0);
40MemberOffset Heap::reference_pendingNext_offset_ = MemberOffset(0);
41MemberOffset Heap::finalizer_reference_zombie_offset_ = MemberOffset(0);
Brian Carlstrom1f870082011-08-23 16:02:11 -070042
Brian Carlstrom395520e2011-09-25 19:35:00 -070043float Heap::target_utilization_ = 0.5;
44
Elliott Hughes92b3b562011-09-08 16:32:26 -070045Mutex* Heap::lock_ = NULL;
46
Elliott Hughes9d5ccec2011-09-19 13:19:50 -070047bool Heap::verify_objects_ = false;
48
Elliott Hughes92b3b562011-09-08 16:32:26 -070049class ScopedHeapLock {
50 public:
51 ScopedHeapLock() {
52 Heap::Lock();
53 }
54
55 ~ScopedHeapLock() {
56 Heap::Unlock();
57 }
58};
59
Elliott Hughesbe759c62011-09-08 19:38:21 -070060void Heap::Init(size_t initial_size, size_t maximum_size,
Brian Carlstrom58ae9412011-10-04 00:56:06 -070061 const std::vector<std::string>& image_file_names) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -070062 const Runtime* runtime = Runtime::Current();
63 if (runtime->IsVerboseStartup()) {
64 LOG(INFO) << "Heap::Init entering";
65 }
66
Brian Carlstrom58ae9412011-10-04 00:56:06 -070067 // bounds of all spaces for allocating live and mark bitmaps
68 // there will be at least one space (the alloc space),
69 // so set to base to max and limit to min to start
70 byte* base = reinterpret_cast<byte*>(std::numeric_limits<uintptr_t>::max());
71 byte* limit = reinterpret_cast<byte*>(std::numeric_limits<uintptr_t>::min());
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070072
Brian Carlstrom58ae9412011-10-04 00:56:06 -070073 byte* requested_base = NULL;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070074 std::vector<Space*> image_spaces;
75 for (size_t i = 0; i < image_file_names.size(); i++) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -070076 Space* space = Space::CreateFromImage(image_file_names[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070077 if (space == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -070078 LOG(FATAL) << "Failed to create space from " << image_file_names[i];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070079 }
80 image_spaces.push_back(space);
81 spaces_.push_back(space);
Brian Carlstrome24fa612011-09-29 00:53:55 -070082 byte* oat_limit_addr = space->GetImageHeader().GetOatLimitAddr();
Brian Carlstrom58ae9412011-10-04 00:56:06 -070083 if (oat_limit_addr > requested_base) {
84 requested_base = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_limit_addr),
85 kPageSize));
86 }
87 base = std::min(base, space->GetBase());
88 limit = std::max(limit, space->GetLimit());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070089 }
90
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070091 Space* space = Space::Create(initial_size, maximum_size, requested_base);
Carl Shapiro58551df2011-07-24 03:09:51 -070092 if (space == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -070093 LOG(FATAL) << "Failed to create alloc space";
Carl Shapiro69759ea2011-07-21 18:13:35 -070094 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -070095 base = std::min(base, space->GetBase());
96 limit = std::max(limit, space->GetLimit());
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070097 DCHECK_LT(base, limit);
98 size_t num_bytes = limit - base;
Carl Shapiro69759ea2011-07-21 18:13:35 -070099
100 // Allocate the initial live bitmap.
Elliott Hughes90a33692011-08-30 13:27:07 -0700101 UniquePtr<HeapBitmap> live_bitmap(HeapBitmap::Create(base, num_bytes));
102 if (live_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700103 LOG(FATAL) << "Failed to create live bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700104 }
105
106 // Allocate the initial mark bitmap.
Elliott Hughes90a33692011-08-30 13:27:07 -0700107 UniquePtr<HeapBitmap> mark_bitmap(HeapBitmap::Create(base, num_bytes));
108 if (mark_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700109 LOG(FATAL) << "Failed to create mark bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700110 }
111
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700112 alloc_space_ = space;
Carl Shapiro58551df2011-07-24 03:09:51 -0700113 spaces_.push_back(space);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700114 maximum_size_ = maximum_size;
115 live_bitmap_ = live_bitmap.release();
116 mark_bitmap_ = mark_bitmap.release();
117
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700118 num_bytes_allocated_ = 0;
119 num_objects_allocated_ = 0;
120
Carl Shapiro69759ea2011-07-21 18:13:35 -0700121 // TODO: allocate the card table
122
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700123 // Make image objects live (after live_bitmap_ is set)
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700124 for (size_t i = 0; i < image_spaces.size(); i++) {
125 RecordImageAllocations(image_spaces[i]);
126 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700127
Elliott Hughes85d15452011-09-16 17:33:01 -0700128 Heap::EnableObjectValidation();
129
Elliott Hughes92b3b562011-09-08 16:32:26 -0700130 // It's still to early to take a lock because there are no threads yet,
131 // but we can create the heap lock now. We don't create it earlier to
132 // make it clear that you can't use locks during heap initialization.
Elliott Hughes8daa0922011-09-11 13:46:25 -0700133 lock_ = new Mutex("Heap lock");
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700134
135 if (runtime->IsVerboseStartup()) {
136 LOG(INFO) << "Heap::Init exiting";
137 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700138}
139
140void Heap::Destroy() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700141 ScopedHeapLock lock;
Carl Shapiro58551df2011-07-24 03:09:51 -0700142 STLDeleteElements(&spaces_);
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700143 if (mark_bitmap_ != NULL) {
144 delete mark_bitmap_;
145 mark_bitmap_ = NULL;
146 }
147 if (live_bitmap_ != NULL) {
148 delete live_bitmap_;
149 }
150 live_bitmap_ = NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700151}
152
Elliott Hughes418dfe72011-10-06 18:56:27 -0700153Object* Heap::AllocObject(Class* klass, size_t byte_count) {
154 {
155 ScopedHeapLock lock;
156 DCHECK(klass == NULL || klass->GetDescriptor() == NULL ||
157 (klass->IsClassClass() && byte_count >= sizeof(Class)) ||
158 (klass->IsVariableSize() || klass->GetObjectSize() == byte_count));
159 DCHECK_GE(byte_count, sizeof(Object));
160 Object* obj = AllocateLocked(byte_count);
161 if (obj != NULL) {
162 obj->SetClass(klass);
163 return obj;
164 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700165 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700166
167 Thread::Current()->ThrowOutOfMemoryError(klass, byte_count);
168 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700169}
170
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700171bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700172 // Note: we deliberately don't take the lock here, and mustn't test anything that would
173 // require taking the lock.
Elliott Hughesa2501992011-08-26 19:39:54 -0700174 if (!IsAligned(obj, kObjectAlignment)) {
175 return false;
176 }
177 // TODO
178 return true;
179}
180
Elliott Hughes3e465b12011-09-02 18:26:12 -0700181#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700182void Heap::VerifyObject(const Object* obj) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700183 if (!verify_objects_) {
184 return;
185 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700186 ScopedHeapLock lock;
187 Heap::VerifyObjectLocked(obj);
188}
189#endif
190
191void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700192 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700193 if (obj != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700194 if (!IsAligned(obj, kObjectAlignment)) {
195 LOG(FATAL) << "Object isn't aligned: " << obj;
196 } else if (!live_bitmap_->Test(obj)) {
197 // TODO: we don't hold a lock here as it is assumed the live bit map
198 // isn't changing if the mutator is running.
199 LOG(FATAL) << "Object is dead: " << obj;
200 }
201 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700202 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700203 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
204 Object::ClassOffset().Int32Value();
205 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
206 if (c == NULL) {
207 LOG(FATAL) << "Null class" << " in object: " << obj;
208 } else if (!IsAligned(c, kObjectAlignment)) {
209 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
210 } else if (!live_bitmap_->Test(c)) {
211 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
212 }
213 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700214 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700215 // that we don't want to run
216 raw_addr = reinterpret_cast<const byte*>(c) +
217 Object::ClassOffset().Int32Value();
218 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
219 raw_addr = reinterpret_cast<const byte*>(c_c) +
220 Object::ClassOffset().Int32Value();
221 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
222 CHECK_EQ(c_c, c_c_c);
223 }
224 }
225}
226
Brian Carlstrom78128a62011-09-15 17:21:19 -0700227void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700228 DCHECK(obj != NULL);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700229 Heap::VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700230}
231
232void Heap::VerifyHeap() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700233 ScopedHeapLock lock;
234 live_bitmap_->Walk(Heap::VerificationCallback, NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700235}
236
Elliott Hughes92b3b562011-09-08 16:32:26 -0700237void Heap::RecordAllocationLocked(Space* space, const Object* obj) {
238#ifndef NDEBUG
239 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700240 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700241 }
242#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700243 size_t size = space->AllocationSize(obj);
244 DCHECK_NE(size, 0u);
245 num_bytes_allocated_ += size;
246 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700247
248 if (Runtime::Current()->HasStatsEnabled()) {
249 RuntimeStats* global_stats = Runtime::Current()->GetStats();
250 RuntimeStats* thread_stats = Thread::Current()->GetStats();
251 ++global_stats->allocated_objects;
252 ++thread_stats->allocated_objects;
253 global_stats->allocated_bytes += size;
254 thread_stats->allocated_bytes += size;
255 }
256
Carl Shapiro58551df2011-07-24 03:09:51 -0700257 live_bitmap_->Set(obj);
258}
259
Elliott Hughes92b3b562011-09-08 16:32:26 -0700260void Heap::RecordFreeLocked(Space* space, const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700261 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700262 size_t size = space->AllocationSize(obj);
263 DCHECK_NE(size, 0u);
264 if (size < num_bytes_allocated_) {
265 num_bytes_allocated_ -= size;
266 } else {
267 num_bytes_allocated_ = 0;
268 }
269 live_bitmap_->Clear(obj);
270 if (num_objects_allocated_ > 0) {
271 num_objects_allocated_ -= 1;
272 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700273
274 if (Runtime::Current()->HasStatsEnabled()) {
275 RuntimeStats* global_stats = Runtime::Current()->GetStats();
276 RuntimeStats* thread_stats = Thread::Current()->GetStats();
277 ++global_stats->freed_objects;
278 ++thread_stats->freed_objects;
279 global_stats->freed_bytes += size;
280 thread_stats->freed_bytes += size;
281 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700282}
283
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700284void Heap::RecordImageAllocations(Space* space) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700285 const Runtime* runtime = Runtime::Current();
286 if (runtime->IsVerboseStartup()) {
287 LOG(INFO) << "Heap::RecordImageAllocations entering";
288 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700289 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700290 CHECK(space != NULL);
291 CHECK(live_bitmap_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292 byte* current = space->GetBase() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700293 while (current < space->GetLimit()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700294 DCHECK(IsAligned(current, kObjectAlignment));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700295 const Object* obj = reinterpret_cast<const Object*>(current);
296 live_bitmap_->Set(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297 current += RoundUp(obj->SizeOf(), kObjectAlignment);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700298 }
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700299 if (runtime->IsVerboseStartup()) {
300 LOG(INFO) << "Heap::RecordImageAllocations exiting";
301 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700302}
303
Elliott Hughes92b3b562011-09-08 16:32:26 -0700304Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700305 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700306 DCHECK(alloc_space_ != NULL);
307 Space* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700308 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700309 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700310 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700311 }
312 return obj;
313}
314
Elliott Hughes92b3b562011-09-08 16:32:26 -0700315Object* Heap::AllocateLocked(Space* space, size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700316 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700317
Carl Shapiro69759ea2011-07-21 18:13:35 -0700318 // Fail impossible allocations. TODO: collect soft references.
319 if (size > maximum_size_) {
320 return NULL;
321 }
322
Carl Shapiro58551df2011-07-24 03:09:51 -0700323 Object* ptr = space->AllocWithoutGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700324 if (ptr != NULL) {
325 return ptr;
326 }
327
328 // The allocation failed. If the GC is running, block until it
329 // completes and retry.
330 if (is_gc_running_) {
331 // The GC is concurrently tracing the heap. Release the heap
332 // lock, wait for the GC to complete, and retrying allocating.
333 WaitForConcurrentGcToComplete();
Carl Shapiro58551df2011-07-24 03:09:51 -0700334 ptr = space->AllocWithoutGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700335 if (ptr != NULL) {
336 return ptr;
337 }
338 }
339
340 // Another failure. Our thread was starved or there may be too many
341 // live objects. Try a foreground GC. This will have no effect if
342 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700343 if (Runtime::Current()->HasStatsEnabled()) {
344 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
345 ++Thread::Current()->GetStats()->gc_for_alloc_count;
346 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700347 LOG(INFO) << "GC_FOR_ALLOC: AllocWithoutGrowth: TODO: test";
Carl Shapiro58551df2011-07-24 03:09:51 -0700348 CollectGarbageInternal();
349 ptr = space->AllocWithoutGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700350 if (ptr != NULL) {
351 return ptr;
352 }
353
Elliott Hughes418dfe72011-10-06 18:56:27 -0700354 LOG(INFO) << "GC_FOR_ALLOC: AllocWithGrowth: TODO: test";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700355 // Even that didn't work; this is an exceptional state.
356 // Try harder, growing the heap if necessary.
Carl Shapiro58551df2011-07-24 03:09:51 -0700357 ptr = space->AllocWithGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700358 if (ptr != NULL) {
359 //size_t new_footprint = dvmHeapSourceGetIdealFootprint();
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700360 size_t new_footprint = space->GetMaxAllowedFootprint();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700361 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700362 // free space is equal to the old free space + the
363 // utilization slop for the new allocation.
364 LOG(INFO) << "Grow heap (frag case) to " << new_footprint / MB
Carl Shapiro69759ea2011-07-21 18:13:35 -0700365 << "for " << size << "-byte allocation";
366 return ptr;
367 }
368
369 // Most allocations should have succeeded by now, so the heap is
370 // really full, really fragmented, or the requested size is really
371 // big. Do another GC, collecting SoftReferences this time. The VM
372 // spec requires that all SoftReferences have been collected and
373 // cleared before throwing an OOME.
374
Elliott Hughes418dfe72011-10-06 18:56:27 -0700375 // OLD-TODO: wait for the finalizers from the previous GC to finish
Carl Shapiro69759ea2011-07-21 18:13:35 -0700376 LOG(INFO) << "Forcing collection of SoftReferences for "
377 << size << "-byte allocation";
Carl Shapiro58551df2011-07-24 03:09:51 -0700378 CollectGarbageInternal();
379 ptr = space->AllocWithGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700380 if (ptr != NULL) {
381 return ptr;
382 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700383
Carl Shapiro69759ea2011-07-21 18:13:35 -0700384 LOG(ERROR) << "Out of memory on a " << size << " byte allocation";
385
Carl Shapiro58551df2011-07-24 03:09:51 -0700386 // TODO: tell the HeapSource to dump its state
387 // TODO: dump stack traces for all threads
Carl Shapiro69759ea2011-07-21 18:13:35 -0700388
Carl Shapiro69759ea2011-07-21 18:13:35 -0700389 return NULL;
390}
391
Elliott Hughesbf86d042011-08-31 17:53:14 -0700392int64_t Heap::GetMaxMemory() {
393 UNIMPLEMENTED(WARNING);
394 return 0;
395}
396
397int64_t Heap::GetTotalMemory() {
398 UNIMPLEMENTED(WARNING);
399 return 0;
400}
401
402int64_t Heap::GetFreeMemory() {
403 UNIMPLEMENTED(WARNING);
404 return 0;
405}
406
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700407class InstanceCounter {
408 public:
409 InstanceCounter(Class* c, bool count_assignable)
410 : class_(c), count_assignable_(count_assignable), count_(0) {
411 }
412
413 size_t GetCount() {
414 return count_;
415 }
416
417 static void Callback(Object* o, void* arg) {
418 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
419 }
420
421 private:
422 void VisitInstance(Object* o) {
423 Class* instance_class = o->GetClass();
424 if (count_assignable_) {
425 if (instance_class == class_) {
426 ++count_;
427 }
428 } else {
429 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
430 ++count_;
431 }
432 }
433 }
434
435 Class* class_;
436 bool count_assignable_;
437 size_t count_;
438};
439
440int64_t Heap::CountInstances(Class* c, bool count_assignable) {
441 ScopedHeapLock lock;
442 InstanceCounter counter(c, count_assignable);
443 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
444 return counter.GetCount();
445}
446
Carl Shapiro69759ea2011-07-21 18:13:35 -0700447void Heap::CollectGarbage() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700448 ScopedHeapLock lock;
Carl Shapiro58551df2011-07-24 03:09:51 -0700449 CollectGarbageInternal();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700450}
451
452void Heap::CollectGarbageInternal() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700453 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700454
Elliott Hughes8d768a92011-09-14 16:35:25 -0700455 ThreadList* thread_list = Runtime::Current()->GetThreadList();
456 thread_list->SuspendAll();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700457
458 size_t initial_size = num_bytes_allocated_;
459 uint64_t t0 = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700460 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700461 {
462 MarkSweep mark_sweep;
463
464 mark_sweep.Init();
465
466 mark_sweep.MarkRoots();
467
468 // Push marked roots onto the mark stack
469
470 // TODO: if concurrent
471 // unlock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700472 // thread_list->ResumeAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700473
474 mark_sweep.RecursiveMark();
475
476 // TODO: if concurrent
477 // lock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700478 // thread_list->SuspendAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700479 // re-mark root set
480 // scan dirty objects
481
482 mark_sweep.ProcessReferences(false);
483
Elliott Hughes2da50362011-10-10 16:57:08 -0700484 // TODO: if concurrent
485 // swap bitmaps
Carl Shapiro58551df2011-07-24 03:09:51 -0700486
487 mark_sweep.Sweep();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700488
489 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700490 }
491
492 GrowForUtilization();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700493 uint64_t t1 = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700494 thread_list->ResumeAll();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700495
496 EnqueueClearedReferences(&cleared_references);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700497
498 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
499 size_t bytes_freed = initial_size - num_bytes_allocated_;
500 bool is_small = (bytes_freed > 0 && bytes_freed < 1024);
501 size_t kib_freed = (bytes_freed > 0 ? std::max(bytes_freed/1024, 1U) : 0);
502
503 size_t footprint = alloc_space_->Size();
504 size_t percentFree = 100 - static_cast<size_t>(100.0f * float(num_bytes_allocated_) / footprint);
505
506 uint32_t duration = (t1 - t0)/1000/1000;
507 LOG(INFO) << "GC freed " << (is_small ? "<" : "") << kib_freed << "KiB, "
508 << percentFree << "% free "
509 << (num_bytes_allocated_/1024) << "KiB/" << (footprint/1024) << "KiB, "
510 << "paused " << duration << "ms";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700511}
512
513void Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700514 lock_->AssertHeld();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700515}
516
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700517/* Terminology:
518 * 1. Footprint: Capacity we allocate from system.
519 * 2. Active space: a.k.a. alloc_space_.
520 * 3. Soft footprint: external allocation + spaces footprint + active space footprint
521 * 4. Overhead: soft footprint excluding active.
522 *
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700523 * Layout: (The spaces below might not be contiguous, but are lumped together to depict size.)
524 * |----------------------spaces footprint--------- --------------|----active space footprint----|
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700525 * |--active space allocated--|
526 * |--------------------soft footprint (include active)--------------------------------------|
527 * |----------------soft footprint excluding active---------------|
528 * |------------soft limit-------...|
529 * |------------------------------------ideal footprint-----------------------------------------...|
530 *
531 */
532
533// Sets the maximum number of bytes that the heap is allowed to
534// allocate from the system. Clamps to the appropriate maximum
535// value.
536// Old spaces will count against the ideal size.
537//
538void Heap::SetIdealFootprint(size_t max_allowed_footprint)
539{
540 if (max_allowed_footprint > Heap::maximum_size_) {
541 LOG(INFO) << "Clamp target GC heap from " << max_allowed_footprint
542 << " to " << Heap::maximum_size_;
543 max_allowed_footprint = Heap::maximum_size_;
544 }
545
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700546 alloc_space_->SetMaxAllowedFootprint(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700547}
548
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700549// kHeapIdealFree is the ideal maximum free size, when we grow the heap for
550// utlization.
551static const size_t kHeapIdealFree = 2 * MB;
552// kHeapMinFree guarantees that you always have at least 512 KB free, when
553// you grow for utilization, regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700554static const size_t kHeapMinFree = kHeapIdealFree / 4;
555
556// Given the current contents of the active space, increase the allowed
Carl Shapiro69759ea2011-07-21 18:13:35 -0700557// heap footprint to match the target utilization ratio. This should
558// only be called immediately after a full garbage collection.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700559//
Carl Shapiro69759ea2011-07-21 18:13:35 -0700560void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700561 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700562
563 // We know what our utilization is at this moment.
564 // This doesn't actually resize any memory. It just lets the heap grow more
565 // when necessary.
566 size_t target_size = size_t( num_bytes_allocated_ /
567 Heap::GetTargetHeapUtilization() );
568
569 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
570 target_size = num_bytes_allocated_ + kHeapIdealFree;
571 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
572 target_size = num_bytes_allocated_ + kHeapMinFree;
573 }
574
575 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700576}
577
Elliott Hughes92b3b562011-09-08 16:32:26 -0700578void Heap::Lock() {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700579 // TODO: grab the lock, but put ourselves into Thread::kVmWait if it looks like
Elliott Hughes92b3b562011-09-08 16:32:26 -0700580 // we're going to have to wait on the mutex.
581 lock_->Lock();
582}
583
584void Heap::Unlock() {
585 lock_->Unlock();
586}
587
Elliott Hughesadb460d2011-10-05 17:02:34 -0700588void Heap::SetWellKnownClasses(Class* java_lang_ref_FinalizerReference,
589 Class* java_lang_ref_ReferenceQueue) {
590 java_lang_ref_FinalizerReference_ = java_lang_ref_FinalizerReference;
591 java_lang_ref_ReferenceQueue_ = java_lang_ref_ReferenceQueue;
592 CHECK(java_lang_ref_FinalizerReference_ != NULL);
593 CHECK(java_lang_ref_ReferenceQueue_ != NULL);
594}
595
596void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
597 MemberOffset reference_queue_offset,
598 MemberOffset reference_queueNext_offset,
599 MemberOffset reference_pendingNext_offset,
600 MemberOffset finalizer_reference_zombie_offset) {
601 reference_referent_offset_ = reference_referent_offset;
602 reference_queue_offset_ = reference_queue_offset;
603 reference_queueNext_offset_ = reference_queueNext_offset;
604 reference_pendingNext_offset_ = reference_pendingNext_offset;
605 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
606 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
607 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
608 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
609 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
610 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
611}
612
613Object* Heap::GetReferenceReferent(Object* reference) {
614 DCHECK(reference != NULL);
615 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
616 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
617}
618
619void Heap::ClearReferenceReferent(Object* reference) {
620 DCHECK(reference != NULL);
621 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
622 reference->SetFieldObject(reference_referent_offset_, NULL, true);
623}
624
625// Returns true if the reference object has not yet been enqueued.
626bool Heap::IsEnqueuable(const Object* ref) {
627 DCHECK(ref != NULL);
628 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
629 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
630 return (queue != NULL) && (queue_next == NULL);
631}
632
633void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
634 DCHECK(ref != NULL);
635 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
636 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
637 EnqueuePendingReference(ref, cleared_reference_list);
638}
639
640void Heap::EnqueuePendingReference(Object* ref, Object** list) {
641 DCHECK(ref != NULL);
642 DCHECK(list != NULL);
643
644 if (*list == NULL) {
645 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
646 *list = ref;
647 } else {
648 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
649 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
650 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
651 }
652}
653
654Object* Heap::DequeuePendingReference(Object** list) {
655 DCHECK(list != NULL);
656 DCHECK(*list != NULL);
657 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
658 Object* ref;
659 if (*list == head) {
660 ref = *list;
661 *list = NULL;
662 } else {
663 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
664 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
665 ref = head;
666 }
667 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
668 return ref;
669}
670
671void Heap::AddFinalizerReference(Object* object) {
672 static Method* FinalizerReference_add =
673 java_lang_ref_FinalizerReference_->FindDirectMethod("add", "(Ljava/lang/Object;)V");
674 DCHECK(FinalizerReference_add != NULL);
675 Object* args[] = { object };
676 FinalizerReference_add->Invoke(Thread::Current(), NULL, reinterpret_cast<byte*>(&args), NULL);
677}
678
679void Heap::EnqueueClearedReferences(Object** cleared) {
680 DCHECK(cleared != NULL);
681 if (*cleared != NULL) {
682 static Method* ReferenceQueue_add =
683 java_lang_ref_ReferenceQueue_->FindDirectMethod("add", "(Ljava/lang/ref/Reference;)V");
684 DCHECK(ReferenceQueue_add != NULL);
685
686 Thread* self = Thread::Current();
687 ScopedThreadStateChange tsc(self, Thread::kRunnable);
688 Object* args[] = { *cleared };
689 ReferenceQueue_add->Invoke(self, NULL, reinterpret_cast<byte*>(&args), NULL);
690 *cleared = NULL;
691 }
692}
693
Carl Shapiro69759ea2011-07-21 18:13:35 -0700694} // namespace art