blob: 3f42c6b1c2e963d0644bb19923a6c135df549396 [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 Hughesadb460d2011-10-05 17:02:34 -0700457 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700458 {
459 MarkSweep mark_sweep;
460
461 mark_sweep.Init();
462
463 mark_sweep.MarkRoots();
464
465 // Push marked roots onto the mark stack
466
467 // TODO: if concurrent
468 // unlock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700469 // thread_list->ResumeAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700470
471 mark_sweep.RecursiveMark();
472
473 // TODO: if concurrent
474 // lock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700475 // thread_list->SuspendAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700476 // re-mark root set
477 // scan dirty objects
478
479 mark_sweep.ProcessReferences(false);
480
Elliott Hughes2da50362011-10-10 16:57:08 -0700481 // TODO: if concurrent
482 // swap bitmaps
Carl Shapiro58551df2011-07-24 03:09:51 -0700483
484 mark_sweep.Sweep();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700485
486 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700487 }
488
489 GrowForUtilization();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700490 thread_list->ResumeAll();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700491
492 EnqueueClearedReferences(&cleared_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700493}
494
495void Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700496 lock_->AssertHeld();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700497}
498
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700499/* Terminology:
500 * 1. Footprint: Capacity we allocate from system.
501 * 2. Active space: a.k.a. alloc_space_.
502 * 3. Soft footprint: external allocation + spaces footprint + active space footprint
503 * 4. Overhead: soft footprint excluding active.
504 *
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700505 * Layout: (The spaces below might not be contiguous, but are lumped together to depict size.)
506 * |----------------------spaces footprint--------- --------------|----active space footprint----|
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700507 * |--active space allocated--|
508 * |--------------------soft footprint (include active)--------------------------------------|
509 * |----------------soft footprint excluding active---------------|
510 * |------------soft limit-------...|
511 * |------------------------------------ideal footprint-----------------------------------------...|
512 *
513 */
514
515// Sets the maximum number of bytes that the heap is allowed to
516// allocate from the system. Clamps to the appropriate maximum
517// value.
518// Old spaces will count against the ideal size.
519//
520void Heap::SetIdealFootprint(size_t max_allowed_footprint)
521{
522 if (max_allowed_footprint > Heap::maximum_size_) {
523 LOG(INFO) << "Clamp target GC heap from " << max_allowed_footprint
524 << " to " << Heap::maximum_size_;
525 max_allowed_footprint = Heap::maximum_size_;
526 }
527
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700528 alloc_space_->SetMaxAllowedFootprint(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700529}
530
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700531// kHeapIdealFree is the ideal maximum free size, when we grow the heap for
532// utlization.
533static const size_t kHeapIdealFree = 2 * MB;
534// kHeapMinFree guarantees that you always have at least 512 KB free, when
535// you grow for utilization, regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700536static const size_t kHeapMinFree = kHeapIdealFree / 4;
537
538// Given the current contents of the active space, increase the allowed
Carl Shapiro69759ea2011-07-21 18:13:35 -0700539// heap footprint to match the target utilization ratio. This should
540// only be called immediately after a full garbage collection.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700541//
Carl Shapiro69759ea2011-07-21 18:13:35 -0700542void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700543 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700544
545 // We know what our utilization is at this moment.
546 // This doesn't actually resize any memory. It just lets the heap grow more
547 // when necessary.
548 size_t target_size = size_t( num_bytes_allocated_ /
549 Heap::GetTargetHeapUtilization() );
550
551 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
552 target_size = num_bytes_allocated_ + kHeapIdealFree;
553 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
554 target_size = num_bytes_allocated_ + kHeapMinFree;
555 }
556
557 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700558}
559
Elliott Hughes92b3b562011-09-08 16:32:26 -0700560void Heap::Lock() {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700561 // TODO: grab the lock, but put ourselves into Thread::kVmWait if it looks like
Elliott Hughes92b3b562011-09-08 16:32:26 -0700562 // we're going to have to wait on the mutex.
563 lock_->Lock();
564}
565
566void Heap::Unlock() {
567 lock_->Unlock();
568}
569
Elliott Hughesadb460d2011-10-05 17:02:34 -0700570void Heap::SetWellKnownClasses(Class* java_lang_ref_FinalizerReference,
571 Class* java_lang_ref_ReferenceQueue) {
572 java_lang_ref_FinalizerReference_ = java_lang_ref_FinalizerReference;
573 java_lang_ref_ReferenceQueue_ = java_lang_ref_ReferenceQueue;
574 CHECK(java_lang_ref_FinalizerReference_ != NULL);
575 CHECK(java_lang_ref_ReferenceQueue_ != NULL);
576}
577
578void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
579 MemberOffset reference_queue_offset,
580 MemberOffset reference_queueNext_offset,
581 MemberOffset reference_pendingNext_offset,
582 MemberOffset finalizer_reference_zombie_offset) {
583 reference_referent_offset_ = reference_referent_offset;
584 reference_queue_offset_ = reference_queue_offset;
585 reference_queueNext_offset_ = reference_queueNext_offset;
586 reference_pendingNext_offset_ = reference_pendingNext_offset;
587 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
588 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
589 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
590 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
591 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
592 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
593}
594
595Object* Heap::GetReferenceReferent(Object* reference) {
596 DCHECK(reference != NULL);
597 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
598 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
599}
600
601void Heap::ClearReferenceReferent(Object* reference) {
602 DCHECK(reference != NULL);
603 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
604 reference->SetFieldObject(reference_referent_offset_, NULL, true);
605}
606
607// Returns true if the reference object has not yet been enqueued.
608bool Heap::IsEnqueuable(const Object* ref) {
609 DCHECK(ref != NULL);
610 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
611 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
612 return (queue != NULL) && (queue_next == NULL);
613}
614
615void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
616 DCHECK(ref != NULL);
617 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
618 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
619 EnqueuePendingReference(ref, cleared_reference_list);
620}
621
622void Heap::EnqueuePendingReference(Object* ref, Object** list) {
623 DCHECK(ref != NULL);
624 DCHECK(list != NULL);
625
626 if (*list == NULL) {
627 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
628 *list = ref;
629 } else {
630 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
631 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
632 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
633 }
634}
635
636Object* Heap::DequeuePendingReference(Object** list) {
637 DCHECK(list != NULL);
638 DCHECK(*list != NULL);
639 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
640 Object* ref;
641 if (*list == head) {
642 ref = *list;
643 *list = NULL;
644 } else {
645 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
646 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
647 ref = head;
648 }
649 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
650 return ref;
651}
652
653void Heap::AddFinalizerReference(Object* object) {
654 static Method* FinalizerReference_add =
655 java_lang_ref_FinalizerReference_->FindDirectMethod("add", "(Ljava/lang/Object;)V");
656 DCHECK(FinalizerReference_add != NULL);
657 Object* args[] = { object };
658 FinalizerReference_add->Invoke(Thread::Current(), NULL, reinterpret_cast<byte*>(&args), NULL);
659}
660
661void Heap::EnqueueClearedReferences(Object** cleared) {
662 DCHECK(cleared != NULL);
663 if (*cleared != NULL) {
664 static Method* ReferenceQueue_add =
665 java_lang_ref_ReferenceQueue_->FindDirectMethod("add", "(Ljava/lang/ref/Reference;)V");
666 DCHECK(ReferenceQueue_add != NULL);
667
668 Thread* self = Thread::Current();
669 ScopedThreadStateChange tsc(self, Thread::kRunnable);
670 Object* args[] = { *cleared };
671 ReferenceQueue_add->Invoke(self, NULL, reinterpret_cast<byte*>(&args), NULL);
672 *cleared = NULL;
673 }
674}
675
Carl Shapiro69759ea2011-07-21 18:13:35 -0700676} // namespace art