blob: 03bbb6abcb36c98a9d8ec58b1158d0bf107faffe [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "mark_sweep.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070018
Carl Shapiro58551df2011-07-24 03:09:51 -070019#include <climits>
20#include <vector>
21
Mathieu Chartier357e9be2012-08-01 11:00:14 -070022#include "card_table.h"
Elliott Hughes410c0c82011-09-01 17:58:25 -070023#include "class_loader.h"
Brian Carlstrom693267a2011-09-06 09:25:34 -070024#include "dex_cache.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070025#include "heap.h"
Elliott Hughes410c0c82011-09-01 17:58:25 -070026#include "indirect_reference_table.h"
27#include "intern_table.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070028#include "jni_internal.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070029#include "large_object_space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070030#include "logging.h"
31#include "macros.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070032#include "monitor.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070033#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070034#include "runtime.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070035#include "space.h"
Elliott Hughes307f75d2011-10-12 18:04:40 -070036#include "timing_logger.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070037#include "thread.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070038#include "thread_list.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070039
Mathieu Chartierd8195f12012-10-05 12:21:28 -070040static const bool kUseMarkStackPrefetch = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -070041
Carl Shapiro69759ea2011-07-21 18:13:35 -070042namespace art {
43
Mathieu Chartier357e9be2012-08-01 11:00:14 -070044class SetFingerVisitor {
45 public:
46 SetFingerVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
47
48 }
49
50 void operator ()(void* finger) const {
51 mark_sweep_->SetFinger(reinterpret_cast<Object*>(finger));
52 }
53
54 private:
55 MarkSweep* const mark_sweep_;
56};
57
Mathieu Chartierd8195f12012-10-05 12:21:28 -070058MarkSweep::MarkSweep(ObjectStack* mark_stack)
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070059 : current_mark_bitmap_(NULL),
60 mark_stack_(mark_stack),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070061 heap_(NULL),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070062 finger_(NULL),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -070063 immune_begin_(NULL),
64 immune_end_(NULL),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070065 soft_reference_list_(NULL),
66 weak_reference_list_(NULL),
67 finalizer_reference_list_(NULL),
68 phantom_reference_list_(NULL),
69 cleared_reference_list_(NULL),
Mathieu Chartier357e9be2012-08-01 11:00:14 -070070 freed_bytes_(0), freed_objects_(0),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070071 class_count_(0), array_count_(0), other_count_(0) {
72 DCHECK(mark_stack_ != NULL);
73}
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080074
Mathieu Chartier5301cd22012-05-31 12:11:36 -070075void MarkSweep::Init() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080076 heap_ = Runtime::Current()->GetHeap();
Mathieu Chartier5301cd22012-05-31 12:11:36 -070077 mark_stack_->Reset();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070078 // TODO: C++0x auto
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070079 FindDefaultMarkBitmap();
buzbee0d966cf2011-09-08 17:34:58 -070080 // TODO: if concurrent, enable card marking in compiler
Carl Shapiro58551df2011-07-24 03:09:51 -070081 // TODO: check that the mark bitmap is entirely clear.
Carl Shapiro58551df2011-07-24 03:09:51 -070082}
83
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070084void MarkSweep::FindDefaultMarkBitmap() {
85 const Spaces& spaces = heap_->GetSpaces();
86 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
87 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect) {
88 current_mark_bitmap_ = (*it)->GetMarkBitmap();
89 CHECK(current_mark_bitmap_ != NULL);
90 return;
91 }
92 }
93 GetHeap()->DumpSpaces();
94 LOG(FATAL) << "Could not find a default mark bitmap";
95}
96
Mathieu Chartier357e9be2012-08-01 11:00:14 -070097inline void MarkSweep::MarkObject0(const Object* obj, bool check_finger) {
Carl Shapiro69759ea2011-07-21 18:13:35 -070098 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070099
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700100 if (obj >= immune_begin_ && obj < immune_end_) {
101 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700102 return;
103 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700104
105 // Try to take advantage of locality of references within a space, failing this find the space
106 // the hard way.
Ian Rogers506de0c2012-09-17 15:39:06 -0700107 if (UNLIKELY(!current_mark_bitmap_->HasAddress(obj))) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700108 SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetSpaceBitmap(obj);
109 if (new_bitmap != NULL) {
110 current_mark_bitmap_ = new_bitmap;
111 } else {
112 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
113 SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
114 if (!large_objects->Test(obj)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700115 if (!large_object_space->Contains(obj)) {
116 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
117 LOG(ERROR) << "Attempting see if it's a bad root";
118 VerifyRoots();
119 LOG(FATAL) << "Can't mark bad root";
120 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700121 large_objects->Set(obj);
122 // Don't need to check finger since large objects never have any object references.
123 }
124 // TODO: Improve clarity of control flow in this function?
125 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700126 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700127 }
128
Carl Shapiro69759ea2011-07-21 18:13:35 -0700129 // This object was not previously marked.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700130 if (!current_mark_bitmap_->Test(obj)) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700131 current_mark_bitmap_->Set(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700132 if (check_finger && obj < finger_) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700133 // Do we need to expand the mark stack?
134 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
135 std::vector<Object*> temp;
136 temp.insert(temp.begin(), mark_stack_->Begin(), mark_stack_->End());
137 mark_stack_->Resize(mark_stack_->Capacity() * 2);
138 for (size_t i = 0; i < temp.size(); ++i) {
139 mark_stack_->PushBack(temp[i]);
140 }
141 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700142 // The object must be pushed on to the mark stack.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700143 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700144 }
145 }
146}
147
148// Used to mark objects when recursing. Recursion is done by moving
149// the finger across the bitmaps in address order and marking child
150// objects. Any newly-marked objects whose addresses are lower than
151// the finger won't be visited by the bitmap scan, so those objects
152// need to be added to the mark stack.
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700153void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700154 if (obj != NULL) {
155 MarkObject0(obj, true);
156 }
157}
158
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700159void MarkSweep::MarkObjectVisitor(const Object* root, void* arg) {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700160 DCHECK(root != NULL);
161 DCHECK(arg != NULL);
162 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Ian Rogers5d76c432011-10-31 21:42:49 -0700163 mark_sweep->MarkObject0(root, false);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700164}
165
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700166void MarkSweep::ReMarkObjectVisitor(const Object* root, void* arg) {
167 DCHECK(root != NULL);
168 DCHECK(arg != NULL);
169 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
170 mark_sweep->MarkObject0(root, true);
171}
172
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700173void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
174 const AbstractMethod* method) {
175 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, method);
176}
177
178void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const AbstractMethod* method) {
179 // See if the root is on any space bitmap.
180 if (heap_->FindSpaceFromObject(root) == NULL) {
181 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
182 if (large_object_space->Contains(root)) {
183 LOG(ERROR) << "Found invalid root: " << root;
184 LOG(ERROR) << "VReg / Shadow frame offset: " << vreg;
185 if (method != NULL) {
186 LOG(ERROR) << "In method " << PrettyMethod(method, true);
187 }
188 }
189 }
190}
191
192void MarkSweep::VerifyRoots() {
193 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
194}
195
Carl Shapiro69759ea2011-07-21 18:13:35 -0700196// Marks all objects in the root set.
197void MarkSweep::MarkRoots() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700198 Runtime::Current()->VisitRoots(MarkObjectVisitor, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700199}
200
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700201class CheckObjectVisitor {
202 public:
203 CheckObjectVisitor(MarkSweep* const mark_sweep)
204 : mark_sweep_(mark_sweep) {
205
206 }
207
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700208 void operator ()(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700209 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
210 Locks::mutator_lock_) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700211 mark_sweep_->CheckReference(obj, ref, offset, is_static);
212 }
213
214 private:
215 MarkSweep* const mark_sweep_;
216};
217
218void MarkSweep::CheckObject(const Object* obj) {
219 DCHECK(obj != NULL);
220 CheckObjectVisitor visitor(this);
221 VisitObjectReferences(obj, visitor);
222}
223
224void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
225 DCHECK(root != NULL);
226 DCHECK(arg != NULL);
227 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700228 DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700229 mark_sweep->CheckObject(root);
230}
231
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700232void MarkSweep::CopyMarkBits(ContinuousSpace* space) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700233 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
234 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
235 mark_bitmap->CopyFrom(live_bitmap);
Ian Rogers5d76c432011-10-31 21:42:49 -0700236}
237
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700238void MarkSweep::BindLiveToMarkBitmap(ContinuousSpace* space) {
239 CHECK(space->IsAllocSpace());
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700240 DlMallocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700241 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
242 SpaceBitmap* mark_bitmap = alloc_space->mark_bitmap_.release();
243 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
244 alloc_space->temp_bitmap_.reset(mark_bitmap);
245 alloc_space->mark_bitmap_.reset(live_bitmap);
246}
247
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700248class ScanImageRootVisitor {
249 public:
250 ScanImageRootVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700251 }
252
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700253 void operator ()(const Object* root) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700254 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_)
255 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700256 DCHECK(root != NULL);
257 mark_sweep_->ScanObject(root);
258 }
259
260 private:
261 MarkSweep* const mark_sweep_;
262};
263
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700264void MarkSweep::ScanGrayObjects(bool update_finger) {
265 const Spaces& spaces = heap_->GetSpaces();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700266 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700267 ScanImageRootVisitor image_root_visitor(this);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700268 SetFingerVisitor finger_visitor(this);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700269 // TODO: C++ 0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700270 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700271 ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700272 byte* begin = space->Begin();
273 byte* end = space->End();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700274 // Image spaces are handled properly since live == marked for them.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700275 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
276 if (update_finger) {
277 card_table->Scan(mark_bitmap, begin, end, image_root_visitor, finger_visitor);
278 } else {
279 card_table->Scan(mark_bitmap, begin, end, image_root_visitor, IdentityFunctor());
280 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700281 }
282}
283
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700284class CheckBitmapVisitor {
285 public:
286 CheckBitmapVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {
287
288 }
289
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700290 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700291 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
292 Locks::mutator_lock_) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700293 DCHECK(obj != NULL);
294 mark_sweep_->CheckObject(obj);
295 }
296
297 private:
298 MarkSweep* mark_sweep_;
299};
300
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700301void MarkSweep::VerifyImageRoots() {
302 // Verify roots ensures that all the references inside the image space point
303 // objects which are either in the image space or marked objects in the alloc
304 // space
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700305 CheckBitmapVisitor visitor(this);
306 const Spaces& spaces = heap_->GetSpaces();
307 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700308 if ((*it)->IsImageSpace()) {
309 ImageSpace* space = (*it)->AsImageSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700310 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
311 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
312 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700313 DCHECK(live_bitmap != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700314 live_bitmap->VisitMarkedRange(begin, end, visitor, IdentityFunctor());
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700315 }
316 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700317}
318
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700319class ScanObjectVisitor {
320 public:
321 ScanObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
322
323 }
324
325 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700326 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_)
327 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700328 mark_sweep_->ScanObject(obj);
329 }
330
331 private:
332 MarkSweep* const mark_sweep_;
333};
334
Carl Shapiro58551df2011-07-24 03:09:51 -0700335// Populates the mark stack based on the set of marked objects and
336// recursively marks until the mark stack is emptied.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700337void MarkSweep::RecursiveMark(bool partial, TimingLogger& timings) {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700338 // RecursiveMark will build the lists of known instances of the Reference classes.
339 // See DelayReferenceReferent for details.
340 CHECK(soft_reference_list_ == NULL);
341 CHECK(weak_reference_list_ == NULL);
342 CHECK(finalizer_reference_list_ == NULL);
343 CHECK(phantom_reference_list_ == NULL);
344 CHECK(cleared_reference_list_ == NULL);
345
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700346 const Spaces& spaces = heap_->GetSpaces();
347
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700348 SetFingerVisitor set_finger_visitor(this);
349 ScanObjectVisitor scan_visitor(this);
350 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700351 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700352 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
353 (!partial && space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700354 ) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700355 current_mark_bitmap_ = space->GetMarkBitmap();
356 if (current_mark_bitmap_ == NULL) {
357 GetHeap()->DumpSpaces();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700358 LOG(FATAL) << "invalid bitmap";
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700359 }
360 // This function does not handle heap end increasing, so we must use the space end.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700361 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
362 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700363 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor, set_finger_visitor);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700364 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700365 }
366 finger_ = reinterpret_cast<Object*>(~0);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700367 timings.AddSplit("RecursiveMark");
Ian Rogers5d76c432011-10-31 21:42:49 -0700368 // TODO: tune the frequency of emptying the mark stack
Carl Shapiro58551df2011-07-24 03:09:51 -0700369 ProcessMarkStack();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700370 timings.AddSplit("ProcessMarkStack");
Carl Shapiro58551df2011-07-24 03:09:51 -0700371}
372
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700373void MarkSweep::RecursiveMarkCards(CardTable* card_table, const std::vector<byte*>& cards,
374 TimingLogger& timings) {
375 ScanImageRootVisitor image_root_visitor(this);
376 SetFingerVisitor finger_visitor(this);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700377 const size_t card_count = cards.size();
378 SpaceBitmap* active_bitmap = NULL;
379 for (size_t i = 0;i < card_count;) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700380 Object* start_obj = reinterpret_cast<Object*>(card_table->AddrFromCard(cards[i]));
381 uintptr_t begin = reinterpret_cast<uintptr_t>(start_obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700382 uintptr_t end = begin + CardTable::kCardSize;
383 for (++i; reinterpret_cast<uintptr_t>(cards[i]) == end && i < card_count; ++i) {
384 end += CardTable::kCardSize;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700385 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700386 if (active_bitmap == NULL || !active_bitmap->HasAddress(start_obj)) {
387 active_bitmap = heap_->GetMarkBitmap()->GetSpaceBitmap(start_obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700388#ifndef NDEBUG
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700389 if (active_bitmap == NULL) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700390 GetHeap()->DumpSpaces();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700391 LOG(FATAL) << "Object " << reinterpret_cast<const void*>(start_obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700392 }
393#endif
394 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700395 active_bitmap->VisitMarkedRange(begin, end, image_root_visitor, finger_visitor);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700396 }
397 timings.AddSplit("RecursiveMarkCards");
398 ProcessMarkStack();
399 timings.AddSplit("ProcessMarkStack");
400}
401
402bool MarkSweep::IsMarkedCallback(const Object* object, void* arg) {
403 return
404 reinterpret_cast<MarkSweep*>(arg)->IsMarked(object) ||
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700405 !reinterpret_cast<MarkSweep*>(arg)->GetHeap()->GetLiveBitmap()->Test(object);
406}
407
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700408void MarkSweep::RecursiveMarkDirtyObjects(bool update_finger) {
409 ScanGrayObjects(update_finger);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700410 ProcessMarkStack();
411}
412
Carl Shapiro58551df2011-07-24 03:09:51 -0700413void MarkSweep::ReMarkRoots() {
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700414 Runtime::Current()->VisitRoots(ReMarkObjectVisitor, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700415}
416
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700417void MarkSweep::SweepJniWeakGlobals(Heap::IsMarkedTester is_marked, void* arg) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700418 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
Ian Rogers50b35e22012-10-04 10:09:15 -0700419 MutexLock mu(Thread::Current(), vm->weak_globals_lock);
Elliott Hughes410c0c82011-09-01 17:58:25 -0700420 IndirectReferenceTable* table = &vm->weak_globals;
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700421 typedef IndirectReferenceTable::iterator It; // TODO: C++0x auto
Elliott Hughes410c0c82011-09-01 17:58:25 -0700422 for (It it = table->begin(), end = table->end(); it != end; ++it) {
423 const Object** entry = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700424 if (!is_marked(*entry, arg)) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700425 *entry = kClearedJniWeakGlobal;
426 }
427 }
428}
429
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700430struct ArrayMarkedCheck {
431 ObjectStack* live_stack;
432 MarkSweep* mark_sweep;
433};
434
435// Either marked or not live.
436bool MarkSweep::IsMarkedArrayCallback(const Object* object, void* arg) {
437 ArrayMarkedCheck* array_check = reinterpret_cast<ArrayMarkedCheck*>(arg);
438 if (array_check->mark_sweep->IsMarked(object)) {
439 return true;
440 }
441 ObjectStack* live_stack = array_check->live_stack;
442 return std::find(live_stack->Begin(), live_stack->End(), object) == live_stack->End();
443}
444
445void MarkSweep::SweepSystemWeaksArray(ObjectStack* allocations) {
Mathieu Chartier46a23632012-08-07 18:44:40 -0700446 Runtime* runtime = Runtime::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700447 // The callbacks check
448 // !is_marked where is_marked is the callback but we want
449 // !IsMarked && IsLive
450 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
451 // Or for swapped (IsLive || !IsMarked).
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700452
453 ArrayMarkedCheck visitor;
454 visitor.live_stack = allocations;
455 visitor.mark_sweep = this;
456 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedArrayCallback, &visitor);
457 runtime->GetMonitorList()->SweepMonitorList(IsMarkedArrayCallback, &visitor);
458 SweepJniWeakGlobals(IsMarkedArrayCallback, &visitor);
459}
460
461void MarkSweep::SweepSystemWeaks() {
462 Runtime* runtime = Runtime::Current();
463 // The callbacks check
464 // !is_marked where is_marked is the callback but we want
465 // !IsMarked && IsLive
466 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
467 // Or for swapped (IsLive || !IsMarked).
468 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedCallback, this);
469 runtime->GetMonitorList()->SweepMonitorList(IsMarkedCallback, this);
470 SweepJniWeakGlobals(IsMarkedCallback, this);
Carl Shapiro58551df2011-07-24 03:09:51 -0700471}
472
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700473bool MarkSweep::VerifyIsLiveCallback(const Object* obj, void* arg) {
474 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
475 // We don't actually want to sweep the object, so lets return "marked"
476 return true;
477}
478
479void MarkSweep::VerifyIsLive(const Object* obj) {
480 Heap* heap = GetHeap();
481 if (!heap->GetLiveBitmap()->Test(obj)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700482 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
483 if (!large_object_space->GetLiveObjects()->Test(obj)) {
484 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
485 heap->allocation_stack_->End()) {
486 // Object not found!
487 heap->DumpSpaces();
488 LOG(FATAL) << "Found dead object " << obj;
489 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700490 }
491 }
492}
493
494void MarkSweep::VerifySystemWeaks() {
495 Runtime* runtime = Runtime::Current();
496 // Verify system weaks, uses a special IsMarked callback which always returns true.
497 runtime->GetInternTable()->SweepInternTableWeaks(VerifyIsLiveCallback, this);
498 runtime->GetMonitorList()->SweepMonitorList(VerifyIsLiveCallback, this);
499
500 JavaVMExt* vm = runtime->GetJavaVM();
Ian Rogers50b35e22012-10-04 10:09:15 -0700501 MutexLock mu(Thread::Current(), vm->weak_globals_lock);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700502 IndirectReferenceTable* table = &vm->weak_globals;
503 typedef IndirectReferenceTable::iterator It; // TODO: C++0x auto
504 for (It it = table->begin(), end = table->end(); it != end; ++it) {
505 const Object** entry = *it;
506 VerifyIsLive(*entry);
507 }
508}
509
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800510struct SweepCallbackContext {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700511 MarkSweep* mark_sweep;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800512 AllocSpace* space;
Ian Rogers50b35e22012-10-04 10:09:15 -0700513 Thread* self;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800514};
515
Ian Rogers30fab402012-01-23 15:43:46 -0800516void MarkSweep::SweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Elliott Hughes307f75d2011-10-12 18:04:40 -0700517 size_t freed_objects = num_ptrs;
518 size_t freed_bytes = 0;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800519 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700520 MarkSweep* mark_sweep = context->mark_sweep;
521 Heap* heap = mark_sweep->GetHeap();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800522 AllocSpace* space = context->space;
Ian Rogers50b35e22012-10-04 10:09:15 -0700523 Thread* self = context->self;
524 Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
Ian Rogers5d76c432011-10-31 21:42:49 -0700525 // Use a bulk free, that merges consecutive objects before freeing or free per object?
526 // Documentation suggests better free performance with merging, but this may be at the expensive
527 // of allocation.
528 // TODO: investigate performance
Ian Rogers30fab402012-01-23 15:43:46 -0800529 static const bool kUseFreeList = true;
530 if (kUseFreeList) {
Ian Rogers30fab402012-01-23 15:43:46 -0800531 // AllocSpace::FreeList clears the value in ptrs, so perform after clearing the live bit
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700532 freed_bytes += space->FreeList(self, num_ptrs, ptrs);
Ian Rogers5d76c432011-10-31 21:42:49 -0700533 } else {
534 for (size_t i = 0; i < num_ptrs; ++i) {
535 Object* obj = static_cast<Object*>(ptrs[i]);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700536 freed_bytes += space->Free(self, obj);
Ian Rogers5d76c432011-10-31 21:42:49 -0700537 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700538 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700539
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700540 heap->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700541 mark_sweep->freed_objects_ += freed_objects;
542 mark_sweep->freed_bytes_ += freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700543}
544
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700545void MarkSweep::ZygoteSweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700546 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Ian Rogers50b35e22012-10-04 10:09:15 -0700547 Locks::heap_bitmap_lock_->AssertExclusiveHeld(context->self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700548 Heap* heap = context->mark_sweep->GetHeap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700549 // We don't free any actual memory to avoid dirtying the shared zygote pages.
550 for (size_t i = 0; i < num_ptrs; ++i) {
551 Object* obj = static_cast<Object*>(ptrs[i]);
552 heap->GetLiveBitmap()->Clear(obj);
553 heap->GetCardTable()->MarkCard(obj);
554 }
555}
556
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700557void MarkSweep::SweepArray(TimingLogger& logger, ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700558 size_t freed_bytes = 0;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700559 DlMallocSpace* space = heap_->GetAllocSpace();
Elliott Hughes2da50362011-10-10 16:57:08 -0700560
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700561 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
562 // bitmap, resulting in occasional frees of Weaks which are still in use.
563 // TODO: Fix when sweeping weaks works properly with mutators unpaused + allocation list.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700564 SweepSystemWeaksArray(allocations);
565 logger.AddSplit("SweepSystemWeaks");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700566
567 // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
568 // going to free.
569 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
570 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700571 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
572 SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
573 SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700574 if (swap_bitmaps) {
575 std::swap(live_bitmap, mark_bitmap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700576 std::swap(large_live_objects, large_mark_objects);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700577 }
578
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700579 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700580 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700581 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700582 Object** out = objects;
583
584 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -0700585 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700586 for (size_t i = 0;i < count;++i) {
587 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700588 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
589 if (LIKELY(mark_bitmap->HasAddress(obj))) {
590 if (!mark_bitmap->Test(obj)) {
591 // Don't bother un-marking since we clear the mark bitmap anyways.
592 *(out++) = obj;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700593 }
594 } else if (!large_mark_objects->Test(obj)) {
595 ++freed_large_objects;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700596 freed_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700597 }
598 }
599 logger.AddSplit("Process allocation stack");
600
601 size_t freed_objects = out - objects;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700602 freed_bytes += space->FreeList(self, freed_objects, objects);
Mathieu Chartier40e978b2012-09-07 11:38:36 -0700603 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700604 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700605 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes);
Mathieu Chartier40e978b2012-09-07 11:38:36 -0700606 freed_objects_ += freed_objects;
607 freed_bytes_ += freed_bytes;
608 logger.AddSplit("FreeList");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700609 allocations->Reset();
610 logger.AddSplit("Reset stack");
611}
612
613void MarkSweep::Sweep(bool partial, bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700614 DCHECK(mark_stack_->IsEmpty());
615
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700616 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
617 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700618 SweepSystemWeaks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700619
Mathieu Chartier46a23632012-08-07 18:44:40 -0700620 const Spaces& spaces = heap_->GetSpaces();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800621 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700622 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -0700623 scc.self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700624 // TODO: C++0x auto
625 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700626 ContinuousSpace* space = *it;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700627 if (
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700628 space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
629 (!partial && space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700630 ) {
631 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
632 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
633 scc.space = space->AsAllocSpace();
634 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
635 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700636 if (swap_bitmaps) {
637 std::swap(live_bitmap, mark_bitmap);
638 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700639 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700640 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700641 SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
642 &SweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700643 } else {
644 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual memory.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700645 SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
646 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700647 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700648 }
649 }
650}
651
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700652void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
653 // Sweep large objects
654 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700655 SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
656 SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
657 if (swap_bitmaps) {
658 std::swap(large_live_objects, large_mark_objects);
659 }
660 SpaceSetMap::Objects& live_objects = large_live_objects->GetObjects();
661 // O(n*log(n)) but hopefully there are not too many large objects.
662 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700663 size_t freed_bytes = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700664 // TODO: C++0x
Ian Rogers50b35e22012-10-04 10:09:15 -0700665 Thread* self = Thread::Current();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700666 for (SpaceSetMap::Objects::iterator it = live_objects.begin(); it != live_objects.end(); ++it) {
667 if (!large_mark_objects->Test(*it)) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700668 freed_bytes += large_object_space->Free(self, const_cast<Object*>(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700669 ++freed_objects;
670 }
671 }
672 freed_objects_ += freed_objects;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700673 freed_bytes_ += freed_bytes;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700674 // Large objects don't count towards bytes_allocated.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700675 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700676}
677
Carl Shapiro69759ea2011-07-21 18:13:35 -0700678// Scans instance fields.
Elliott Hughesb0663112011-10-19 18:16:37 -0700679inline void MarkSweep::ScanInstanceFields(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700680 DCHECK(obj != NULL);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700681 Class* klass = obj->GetClass();
682 DCHECK(klass != NULL);
Elliott Hughes2da50362011-10-10 16:57:08 -0700683 ScanFields(obj, klass->GetReferenceInstanceOffsets(), false);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700684}
685
686// Scans static storage on a Class.
Elliott Hughesb0663112011-10-19 18:16:37 -0700687inline void MarkSweep::ScanStaticFields(const Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700688 DCHECK(klass != NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700689 ScanFields(klass, klass->GetReferenceStaticOffsets(), true);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700690}
691
Elliott Hughesb0663112011-10-19 18:16:37 -0700692inline void MarkSweep::ScanFields(const Object* obj, uint32_t ref_offsets, bool is_static) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700693 if (ref_offsets != CLASS_WALK_SUPER) {
694 // Found a reference offset bitmap. Mark the specified offsets.
695 while (ref_offsets != 0) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700696 const size_t right_shift = CLZ(ref_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700697 MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
698 const Object* ref = obj->GetFieldObject<const Object*>(byte_offset, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700699 MarkObject(ref);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700700 ref_offsets ^= CLASS_HIGH_BIT >> right_shift;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700701 }
702 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700703 // There is no reference offset bitmap. In the non-static case,
704 // walk up the class inheritance hierarchy and find reference
705 // offsets the hard way. In the static case, just consider this
706 // class.
707 for (const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700708 klass != NULL;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700709 klass = is_static ? NULL : klass->GetSuperClass()) {
710 size_t num_reference_fields = (is_static
711 ? klass->NumReferenceStaticFields()
712 : klass->NumReferenceInstanceFields());
713 for (size_t i = 0; i < num_reference_fields; ++i) {
714 Field* field = (is_static
715 ? klass->GetStaticField(i)
716 : klass->GetInstanceField(i));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700717 MemberOffset field_offset = field->GetOffset();
718 const Object* ref = obj->GetFieldObject<const Object*>(field_offset, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700719 MarkObject(ref);
720 }
721 }
722 }
723}
724
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700725void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700726 const Spaces& spaces = heap_->GetSpaces();
727 // TODO: C++0x auto
728 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
729 if ((*cur)->IsAllocSpace() && (*cur)->Contains(ref)) {
730 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700731
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700732 bool is_marked = IsMarked(ref);
733 if (!is_marked) {
734 LOG(INFO) << **cur;
735 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
736 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
737 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
738 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700739
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700740 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
741 DCHECK(klass != NULL);
742 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
743 DCHECK(fields != NULL);
744 bool found = false;
745 for (int32_t i = 0; i < fields->GetLength(); ++i) {
746 const Field* cur = fields->Get(i);
747 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
748 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
749 found = true;
750 break;
751 }
752 }
753 if (!found) {
754 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
755 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700756
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700757 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
758 if (!obj_marked) {
759 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
760 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
761 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700762 }
763 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700764 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700765 break;
Ian Rogers5d76c432011-10-31 21:42:49 -0700766 }
767}
768
Carl Shapiro69759ea2011-07-21 18:13:35 -0700769// Scans the header, static field references, and interface pointers
770// of a class object.
Elliott Hughesb0663112011-10-19 18:16:37 -0700771inline void MarkSweep::ScanClass(const Object* obj) {
Elliott Hughes352a4242011-10-31 15:15:21 -0700772#ifndef NDEBUG
773 ++class_count_;
774#endif
Brian Carlstrom693267a2011-09-06 09:25:34 -0700775 ScanInstanceFields(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700776 ScanStaticFields(obj->AsClass());
Carl Shapiro69759ea2011-07-21 18:13:35 -0700777}
778
779// Scans the header of all array objects. If the array object is
780// specialized to a reference type, scans the array data as well.
Elliott Hughesb0663112011-10-19 18:16:37 -0700781inline void MarkSweep::ScanArray(const Object* obj) {
Elliott Hughes352a4242011-10-31 15:15:21 -0700782#ifndef NDEBUG
783 ++array_count_;
784#endif
Carl Shapiro69759ea2011-07-21 18:13:35 -0700785 MarkObject(obj->GetClass());
786 if (obj->IsObjectArray()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700787 const ObjectArray<Object>* array = obj->AsObjectArray<Object>();
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700788 for (int32_t i = 0; i < array->GetLength(); ++i) {
Ian Rogers5d76c432011-10-31 21:42:49 -0700789 const Object* element = array->GetWithoutChecks(i);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700790 MarkObject(element);
791 }
792 }
793}
794
Carl Shapiro69759ea2011-07-21 18:13:35 -0700795// Process the "referent" field in a java.lang.ref.Reference. If the
796// referent has not yet been marked, put it on the appropriate list in
797// the gcHeap for later processing.
798void MarkSweep::DelayReferenceReferent(Object* obj) {
799 DCHECK(obj != NULL);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700800 Class* klass = obj->GetClass();
801 DCHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700802 DCHECK(klass->IsReferenceClass());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800803 Object* pending = obj->GetFieldObject<Object*>(heap_->GetReferencePendingNextOffset(), false);
804 Object* referent = heap_->GetReferenceReferent(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700805 if (pending == NULL && referent != NULL && !IsMarked(referent)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700806 Object** list = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700807 if (klass->IsSoftReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700808 list = &soft_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700809 } else if (klass->IsWeakReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700810 list = &weak_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700811 } else if (klass->IsFinalizerReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700812 list = &finalizer_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700813 } else if (klass->IsPhantomReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700814 list = &phantom_reference_list_;
815 }
Brian Carlstrom0796af02011-10-12 14:31:45 -0700816 DCHECK(list != NULL) << PrettyClass(klass) << " " << std::hex << klass->GetAccessFlags();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800817 heap_->EnqueuePendingReference(obj, list);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700818 }
819}
820
821// Scans the header and field references of a data object. If the
822// scanned object is a reference subclass, it is scheduled for later
Elliott Hughesadb460d2011-10-05 17:02:34 -0700823// processing.
Elliott Hughesb0663112011-10-19 18:16:37 -0700824inline void MarkSweep::ScanOther(const Object* obj) {
Elliott Hughes352a4242011-10-31 15:15:21 -0700825#ifndef NDEBUG
826 ++other_count_;
827#endif
Carl Shapiro69759ea2011-07-21 18:13:35 -0700828 ScanInstanceFields(obj);
Elliott Hughes352a4242011-10-31 15:15:21 -0700829 if (obj->GetClass()->IsReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700830 DelayReferenceReferent(const_cast<Object*>(obj));
831 }
832}
833
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700834void MarkSweep::ScanRoot(const Object* obj) {
835 ScanObject(obj);
836}
837
Carl Shapiro69759ea2011-07-21 18:13:35 -0700838// Scans an object reference. Determines the type of the reference
839// and dispatches to a specialized scanning routine.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700840void MarkSweep::ScanObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700841 DCHECK(obj != NULL);
842 DCHECK(obj->GetClass() != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700843#ifndef NDEBUG
844 if (!IsMarked(obj)) {
845 heap_->DumpSpaces();
846 LOG(FATAL) << "Scanning unmarked object " << reinterpret_cast<const void*>(obj);
847 }
848#endif
Carl Shapiro69759ea2011-07-21 18:13:35 -0700849 if (obj->IsClass()) {
850 ScanClass(obj);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700851 } else if (obj->IsArrayInstance()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700852 ScanArray(obj);
853 } else {
Carl Shapiro58551df2011-07-24 03:09:51 -0700854 ScanOther(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700855 }
856}
857
Ian Rogers5d76c432011-10-31 21:42:49 -0700858// Scan anything that's on the mark stack.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700859void MarkSweep::ProcessMarkStack() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700860 if (kUseMarkStackPrefetch) {
861 const size_t fifo_size = 4;
862 const size_t fifo_mask = fifo_size - 1;
863 const Object* fifo[fifo_size];
864 for (size_t i = 0;i < fifo_size;++i) {
865 fifo[i] = NULL;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700866 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700867 size_t fifo_pos = 0;
868 size_t fifo_count = 0;
869 for (;;) {
870 const Object* obj = fifo[fifo_pos & fifo_mask];
871 if (obj != NULL) {
872 ScanObject(obj);
873 fifo[fifo_pos & fifo_mask] = NULL;
874 --fifo_count;
875 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700876
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700877 if (!mark_stack_->IsEmpty()) {
878 const Object* obj = mark_stack_->PopBack();
879 DCHECK(obj != NULL);
880 fifo[fifo_pos & fifo_mask] = obj;
881 __builtin_prefetch(obj);
882 fifo_count++;
883 }
884 fifo_pos++;
885
886 if (!fifo_count) {
887 CHECK(mark_stack_->IsEmpty()) << mark_stack_->Size();
888 break;
889 }
890 }
891 } else {
892 while (!mark_stack_->IsEmpty()) {
893 const Object* obj = mark_stack_->PopBack();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700894 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700895 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700896 }
897 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700898}
899
Carl Shapiro69759ea2011-07-21 18:13:35 -0700900// Walks the reference list marking any references subject to the
901// reference clearing policy. References with a black referent are
902// removed from the list. References with white referents biased
903// toward saving are blackened and also removed from the list.
904void MarkSweep::PreserveSomeSoftReferences(Object** list) {
905 DCHECK(list != NULL);
906 Object* clear = NULL;
907 size_t counter = 0;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700908
909 DCHECK(mark_stack_->IsEmpty());
910
Carl Shapiro69759ea2011-07-21 18:13:35 -0700911 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800912 Object* ref = heap_->DequeuePendingReference(list);
913 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700914 if (referent == NULL) {
915 // Referent was cleared by the user during marking.
916 continue;
917 }
918 bool is_marked = IsMarked(referent);
919 if (!is_marked && ((++counter) & 1)) {
920 // Referent is white and biased toward saving, mark it.
921 MarkObject(referent);
922 is_marked = true;
923 }
924 if (!is_marked) {
925 // Referent is white, queue it for clearing.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800926 heap_->EnqueuePendingReference(ref, &clear);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700927 }
928 }
929 *list = clear;
930 // Restart the mark with the newly black references added to the
931 // root set.
932 ProcessMarkStack();
933}
934
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700935inline bool MarkSweep::IsMarked(const Object* object) const
936 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
937 if (object >= immune_begin_ && object < immune_end_) {
938 return true;
939 }
940 DCHECK(current_mark_bitmap_ != NULL);
941 if (current_mark_bitmap_->HasAddress(object)) {
942 return current_mark_bitmap_->Test(object);
943 }
944 return heap_->GetMarkBitmap()->Test(object);
945}
946
947
Carl Shapiro69759ea2011-07-21 18:13:35 -0700948// Unlink the reference list clearing references objects with white
949// referents. Cleared references registered to a reference queue are
950// scheduled for appending by the heap worker thread.
951void MarkSweep::ClearWhiteReferences(Object** list) {
952 DCHECK(list != NULL);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700953 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800954 Object* ref = heap_->DequeuePendingReference(list);
955 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700956 if (referent != NULL && !IsMarked(referent)) {
957 // Referent is white, clear it.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800958 heap_->ClearReferenceReferent(ref);
959 if (heap_->IsEnqueuable(ref)) {
960 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700961 }
962 }
963 }
964 DCHECK(*list == NULL);
965}
966
967// Enqueues finalizer references with white referents. White
968// referents are blackened, moved to the zombie field, and the
969// referent field is cleared.
970void MarkSweep::EnqueueFinalizerReferences(Object** list) {
971 DCHECK(list != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800972 MemberOffset zombie_offset = heap_->GetFinalizerReferenceZombieOffset();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700973 bool has_enqueued = false;
974 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800975 Object* ref = heap_->DequeuePendingReference(list);
976 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700977 if (referent != NULL && !IsMarked(referent)) {
978 MarkObject(referent);
979 // If the referent is non-null the reference must queuable.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800980 DCHECK(heap_->IsEnqueuable(ref));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700981 ref->SetFieldObject(zombie_offset, referent, false);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800982 heap_->ClearReferenceReferent(ref);
983 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700984 has_enqueued = true;
985 }
986 }
987 if (has_enqueued) {
988 ProcessMarkStack();
989 }
990 DCHECK(*list == NULL);
991}
992
Carl Shapiro58551df2011-07-24 03:09:51 -0700993// Process reference class instances and schedule finalizations.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700994void MarkSweep::ProcessReferences(Object** soft_references, bool clear_soft,
995 Object** weak_references,
996 Object** finalizer_references,
997 Object** phantom_references) {
998 DCHECK(soft_references != NULL);
999 DCHECK(weak_references != NULL);
1000 DCHECK(finalizer_references != NULL);
1001 DCHECK(phantom_references != NULL);
1002
1003 // Unless we are in the zygote or required to clear soft references
1004 // with white references, preserve some white referents.
Ian Rogers2945e242012-06-03 14:45:16 -07001005 if (!clear_soft && !Runtime::Current()->IsZygote()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001006 PreserveSomeSoftReferences(soft_references);
1007 }
1008
1009 // Clear all remaining soft and weak references with white
1010 // referents.
1011 ClearWhiteReferences(soft_references);
1012 ClearWhiteReferences(weak_references);
1013
1014 // Preserve all white objects with finalize methods and schedule
1015 // them for finalization.
1016 EnqueueFinalizerReferences(finalizer_references);
1017
1018 // Clear all f-reachable soft and weak references with white
1019 // referents.
1020 ClearWhiteReferences(soft_references);
1021 ClearWhiteReferences(weak_references);
1022
1023 // Clear all phantom references with white referents.
1024 ClearWhiteReferences(phantom_references);
1025
1026 // At this point all reference lists should be empty.
1027 DCHECK(*soft_references == NULL);
1028 DCHECK(*weak_references == NULL);
1029 DCHECK(*finalizer_references == NULL);
1030 DCHECK(*phantom_references == NULL);
1031}
1032
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001033void MarkSweep::UnBindBitmaps() {
1034 const Spaces& spaces = heap_->GetSpaces();
1035 // TODO: C++0x auto
1036 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
1037 Space* space = *it;
1038 if (space->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001039 DlMallocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001040 if (alloc_space->temp_bitmap_.get() != NULL) {
1041 // At this point, the temp_bitmap holds our old mark bitmap.
1042 SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
1043 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1044 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1045 alloc_space->mark_bitmap_.reset(new_bitmap);
1046 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1047 }
1048 }
1049 }
1050}
1051
Carl Shapiro69759ea2011-07-21 18:13:35 -07001052MarkSweep::~MarkSweep() {
Elliott Hughes352a4242011-10-31 15:15:21 -07001053#ifndef NDEBUG
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001054 VLOG(heap) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_ << " other=" << other_count_;
Elliott Hughes352a4242011-10-31 15:15:21 -07001055#endif
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001056 // Ensure that the mark stack is empty.
1057 CHECK(mark_stack_->IsEmpty());
1058
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001059 // Clear all of the alloc spaces' mark bitmaps.
1060 const Spaces& spaces = heap_->GetSpaces();
1061 // TODO: C++0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001062 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001063 ContinuousSpace* space = *it;
1064 if (space->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1065 space->GetMarkBitmap()->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001066 }
1067 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001068 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001069
1070 // Reset the marked large objects.
1071 LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001072 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001073}
1074
1075} // namespace art