blob: b82bc6e576aef3e8c0e6308e472108ae33e2309e [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"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070029#include "logging.h"
30#include "macros.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070031#include "monitor.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070032#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070033#include "runtime.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070034#include "space.h"
Elliott Hughes307f75d2011-10-12 18:04:40 -070035#include "timing_logger.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070036#include "thread.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070037
Mathieu Chartierd8195f12012-10-05 12:21:28 -070038static const bool kUseMarkStackPrefetch = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -070039
Carl Shapiro69759ea2011-07-21 18:13:35 -070040namespace art {
41
Mathieu Chartier357e9be2012-08-01 11:00:14 -070042class SetFingerVisitor {
43 public:
44 SetFingerVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
45
46 }
47
48 void operator ()(void* finger) const {
49 mark_sweep_->SetFinger(reinterpret_cast<Object*>(finger));
50 }
51
52 private:
53 MarkSweep* const mark_sweep_;
54};
55
Mathieu Chartierd8195f12012-10-05 12:21:28 -070056MarkSweep::MarkSweep(ObjectStack* mark_stack)
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070057 : current_mark_bitmap_(NULL),
58 mark_stack_(mark_stack),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070059 heap_(NULL),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070060 finger_(NULL),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -070061 immune_begin_(NULL),
62 immune_end_(NULL),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070063 soft_reference_list_(NULL),
64 weak_reference_list_(NULL),
65 finalizer_reference_list_(NULL),
66 phantom_reference_list_(NULL),
67 cleared_reference_list_(NULL),
Mathieu Chartier357e9be2012-08-01 11:00:14 -070068 freed_bytes_(0), freed_objects_(0),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070069 class_count_(0), array_count_(0), other_count_(0) {
70 DCHECK(mark_stack_ != NULL);
71}
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080072
Mathieu Chartier5301cd22012-05-31 12:11:36 -070073void MarkSweep::Init() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080074 heap_ = Runtime::Current()->GetHeap();
Mathieu Chartier5301cd22012-05-31 12:11:36 -070075 mark_stack_->Reset();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070076 // TODO: C++0x auto
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070077 FindDefaultMarkBitmap();
buzbee0d966cf2011-09-08 17:34:58 -070078 // TODO: if concurrent, enable card marking in compiler
Carl Shapiro58551df2011-07-24 03:09:51 -070079 // TODO: check that the mark bitmap is entirely clear.
Carl Shapiro58551df2011-07-24 03:09:51 -070080}
81
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070082void MarkSweep::FindDefaultMarkBitmap() {
83 const Spaces& spaces = heap_->GetSpaces();
84 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
85 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect) {
86 current_mark_bitmap_ = (*it)->GetMarkBitmap();
87 CHECK(current_mark_bitmap_ != NULL);
88 return;
89 }
90 }
91 GetHeap()->DumpSpaces();
92 LOG(FATAL) << "Could not find a default mark bitmap";
93}
94
Mathieu Chartier357e9be2012-08-01 11:00:14 -070095inline void MarkSweep::MarkObject0(const Object* obj, bool check_finger) {
Carl Shapiro69759ea2011-07-21 18:13:35 -070096 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070097
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -070098 if (obj >= immune_begin_ && obj < immune_end_) {
99 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700100 return;
101 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700102
103 // Try to take advantage of locality of references within a space, failing this find the space
104 // the hard way.
Ian Rogers506de0c2012-09-17 15:39:06 -0700105 if (UNLIKELY(!current_mark_bitmap_->HasAddress(obj))) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700106 SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetSpaceBitmap(obj);
107 if (new_bitmap != NULL) {
108 current_mark_bitmap_ = new_bitmap;
109 } else {
110 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
111 SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
112 if (!large_objects->Test(obj)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700113 CHECK(large_object_space->Contains(obj)) << "Attempting to mark object " << obj
114 << " not in large object space";
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700115 large_objects->Set(obj);
116 // Don't need to check finger since large objects never have any object references.
117 }
118 // TODO: Improve clarity of control flow in this function?
119 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700120 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700121 }
122
Carl Shapiro69759ea2011-07-21 18:13:35 -0700123 // This object was not previously marked.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700124 if (!current_mark_bitmap_->Test(obj)) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700125 current_mark_bitmap_->Set(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700126 if (check_finger && obj < finger_) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700127 // Do we need to expand the mark stack?
128 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
129 std::vector<Object*> temp;
130 temp.insert(temp.begin(), mark_stack_->Begin(), mark_stack_->End());
131 mark_stack_->Resize(mark_stack_->Capacity() * 2);
132 for (size_t i = 0; i < temp.size(); ++i) {
133 mark_stack_->PushBack(temp[i]);
134 }
135 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700136 // The object must be pushed on to the mark stack.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700137 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700138 }
139 }
140}
141
142// Used to mark objects when recursing. Recursion is done by moving
143// the finger across the bitmaps in address order and marking child
144// objects. Any newly-marked objects whose addresses are lower than
145// the finger won't be visited by the bitmap scan, so those objects
146// need to be added to the mark stack.
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700147void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700148 if (obj != NULL) {
149 MarkObject0(obj, true);
150 }
151}
152
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700153void MarkSweep::MarkObjectVisitor(const Object* root, void* arg) {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700154 DCHECK(root != NULL);
155 DCHECK(arg != NULL);
156 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Ian Rogers5d76c432011-10-31 21:42:49 -0700157 mark_sweep->MarkObject0(root, false);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700158}
159
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700160void MarkSweep::ReMarkObjectVisitor(const Object* root, void* arg) {
161 DCHECK(root != NULL);
162 DCHECK(arg != NULL);
163 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
164 mark_sweep->MarkObject0(root, true);
165}
166
Carl Shapiro69759ea2011-07-21 18:13:35 -0700167// Marks all objects in the root set.
168void MarkSweep::MarkRoots() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700169 Runtime::Current()->VisitRoots(MarkObjectVisitor, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700170}
171
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700172class CheckObjectVisitor {
173 public:
174 CheckObjectVisitor(MarkSweep* const mark_sweep)
175 : mark_sweep_(mark_sweep) {
176
177 }
178
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700179 void operator ()(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700180 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
181 Locks::mutator_lock_) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700182 mark_sweep_->CheckReference(obj, ref, offset, is_static);
183 }
184
185 private:
186 MarkSweep* const mark_sweep_;
187};
188
189void MarkSweep::CheckObject(const Object* obj) {
190 DCHECK(obj != NULL);
191 CheckObjectVisitor visitor(this);
192 VisitObjectReferences(obj, visitor);
193}
194
195void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
196 DCHECK(root != NULL);
197 DCHECK(arg != NULL);
198 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700199 DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700200 mark_sweep->CheckObject(root);
201}
202
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700203void MarkSweep::CopyMarkBits(ContinuousSpace* space) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700204 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
205 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
206 mark_bitmap->CopyFrom(live_bitmap);
Ian Rogers5d76c432011-10-31 21:42:49 -0700207}
208
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700209void MarkSweep::BindLiveToMarkBitmap(ContinuousSpace* space) {
210 CHECK(space->IsAllocSpace());
211 AllocSpace* alloc_space = space->AsAllocSpace();
212 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
213 SpaceBitmap* mark_bitmap = alloc_space->mark_bitmap_.release();
214 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
215 alloc_space->temp_bitmap_.reset(mark_bitmap);
216 alloc_space->mark_bitmap_.reset(live_bitmap);
217}
218
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700219class ScanImageRootVisitor {
220 public:
221 ScanImageRootVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700222 }
223
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700224 void operator ()(const Object* root) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700225 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_)
226 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700227 DCHECK(root != NULL);
228 mark_sweep_->ScanObject(root);
229 }
230
231 private:
232 MarkSweep* const mark_sweep_;
233};
234
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700235void MarkSweep::ScanGrayObjects(bool update_finger) {
236 const Spaces& spaces = heap_->GetSpaces();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700237 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700238 ScanImageRootVisitor image_root_visitor(this);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700239 SetFingerVisitor finger_visitor(this);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700240 // TODO: C++ 0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700241 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700242 ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700243 byte* begin = space->Begin();
244 byte* end = space->End();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700245 // Image spaces are handled properly since live == marked for them.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700246 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
247 if (update_finger) {
248 card_table->Scan(mark_bitmap, begin, end, image_root_visitor, finger_visitor);
249 } else {
250 card_table->Scan(mark_bitmap, begin, end, image_root_visitor, IdentityFunctor());
251 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700252 }
253}
254
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700255class CheckBitmapVisitor {
256 public:
257 CheckBitmapVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {
258
259 }
260
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700261 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700262 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
263 Locks::mutator_lock_) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700264 DCHECK(obj != NULL);
265 mark_sweep_->CheckObject(obj);
266 }
267
268 private:
269 MarkSweep* mark_sweep_;
270};
271
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700272void MarkSweep::VerifyImageRoots() {
273 // Verify roots ensures that all the references inside the image space point
274 // objects which are either in the image space or marked objects in the alloc
275 // space
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700276 CheckBitmapVisitor visitor(this);
277 const Spaces& spaces = heap_->GetSpaces();
278 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700279 if ((*it)->IsImageSpace()) {
280 ImageSpace* space = (*it)->AsImageSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700281 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
282 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
283 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700284 DCHECK(live_bitmap != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700285 live_bitmap->VisitMarkedRange(begin, end, visitor, IdentityFunctor());
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700286 }
287 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700288}
289
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700290class ScanObjectVisitor {
291 public:
292 ScanObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
293
294 }
295
296 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700297 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_)
298 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700299 mark_sweep_->ScanObject(obj);
300 }
301
302 private:
303 MarkSweep* const mark_sweep_;
304};
305
Carl Shapiro58551df2011-07-24 03:09:51 -0700306// Populates the mark stack based on the set of marked objects and
307// recursively marks until the mark stack is emptied.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700308void MarkSweep::RecursiveMark(bool partial, TimingLogger& timings) {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700309 // RecursiveMark will build the lists of known instances of the Reference classes.
310 // See DelayReferenceReferent for details.
311 CHECK(soft_reference_list_ == NULL);
312 CHECK(weak_reference_list_ == NULL);
313 CHECK(finalizer_reference_list_ == NULL);
314 CHECK(phantom_reference_list_ == NULL);
315 CHECK(cleared_reference_list_ == NULL);
316
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700317 const Spaces& spaces = heap_->GetSpaces();
318
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700319 SetFingerVisitor set_finger_visitor(this);
320 ScanObjectVisitor scan_visitor(this);
321 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700322 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700323 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
324 (!partial && space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700325 ) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700326 current_mark_bitmap_ = space->GetMarkBitmap();
327 if (current_mark_bitmap_ == NULL) {
328 GetHeap()->DumpSpaces();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700329 LOG(FATAL) << "invalid bitmap";
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700330 }
331 // This function does not handle heap end increasing, so we must use the space end.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700332 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
333 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700334 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor, set_finger_visitor);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700335 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700336 }
337 finger_ = reinterpret_cast<Object*>(~0);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700338 timings.AddSplit("RecursiveMark");
Ian Rogers5d76c432011-10-31 21:42:49 -0700339 // TODO: tune the frequency of emptying the mark stack
Carl Shapiro58551df2011-07-24 03:09:51 -0700340 ProcessMarkStack();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700341 timings.AddSplit("ProcessMarkStack");
Carl Shapiro58551df2011-07-24 03:09:51 -0700342}
343
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700344void MarkSweep::RecursiveMarkCards(CardTable* card_table, const std::vector<byte*>& cards,
345 TimingLogger& timings) {
346 ScanImageRootVisitor image_root_visitor(this);
347 SetFingerVisitor finger_visitor(this);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700348 const size_t card_count = cards.size();
349 SpaceBitmap* active_bitmap = NULL;
350 for (size_t i = 0;i < card_count;) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700351 Object* start_obj = reinterpret_cast<Object*>(card_table->AddrFromCard(cards[i]));
352 uintptr_t begin = reinterpret_cast<uintptr_t>(start_obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700353 uintptr_t end = begin + CardTable::kCardSize;
354 for (++i; reinterpret_cast<uintptr_t>(cards[i]) == end && i < card_count; ++i) {
355 end += CardTable::kCardSize;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700356 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700357 if (active_bitmap == NULL || !active_bitmap->HasAddress(start_obj)) {
358 active_bitmap = heap_->GetMarkBitmap()->GetSpaceBitmap(start_obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700359#ifndef NDEBUG
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700360 if (active_bitmap == NULL) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700361 GetHeap()->DumpSpaces();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700362 LOG(FATAL) << "Object " << reinterpret_cast<const void*>(start_obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700363 }
364#endif
365 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700366 active_bitmap->VisitMarkedRange(begin, end, image_root_visitor, finger_visitor);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700367 }
368 timings.AddSplit("RecursiveMarkCards");
369 ProcessMarkStack();
370 timings.AddSplit("ProcessMarkStack");
371}
372
373bool MarkSweep::IsMarkedCallback(const Object* object, void* arg) {
374 return
375 reinterpret_cast<MarkSweep*>(arg)->IsMarked(object) ||
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700376 !reinterpret_cast<MarkSweep*>(arg)->GetHeap()->GetLiveBitmap()->Test(object);
377}
378
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700379void MarkSweep::RecursiveMarkDirtyObjects(bool update_finger) {
380 ScanGrayObjects(update_finger);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700381 ProcessMarkStack();
382}
383
Carl Shapiro58551df2011-07-24 03:09:51 -0700384void MarkSweep::ReMarkRoots() {
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700385 Runtime::Current()->VisitRoots(ReMarkObjectVisitor, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700386}
387
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700388void MarkSweep::SweepJniWeakGlobals(Heap::IsMarkedTester is_marked, void* arg) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700389 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
Ian Rogers50b35e22012-10-04 10:09:15 -0700390 MutexLock mu(Thread::Current(), vm->weak_globals_lock);
Elliott Hughes410c0c82011-09-01 17:58:25 -0700391 IndirectReferenceTable* table = &vm->weak_globals;
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700392 typedef IndirectReferenceTable::iterator It; // TODO: C++0x auto
Elliott Hughes410c0c82011-09-01 17:58:25 -0700393 for (It it = table->begin(), end = table->end(); it != end; ++it) {
394 const Object** entry = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700395 if (!is_marked(*entry, arg)) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700396 *entry = kClearedJniWeakGlobal;
397 }
398 }
399}
400
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700401struct ArrayMarkedCheck {
402 ObjectStack* live_stack;
403 MarkSweep* mark_sweep;
404};
405
406// Either marked or not live.
407bool MarkSweep::IsMarkedArrayCallback(const Object* object, void* arg) {
408 ArrayMarkedCheck* array_check = reinterpret_cast<ArrayMarkedCheck*>(arg);
409 if (array_check->mark_sweep->IsMarked(object)) {
410 return true;
411 }
412 ObjectStack* live_stack = array_check->live_stack;
413 return std::find(live_stack->Begin(), live_stack->End(), object) == live_stack->End();
414}
415
416void MarkSweep::SweepSystemWeaksArray(ObjectStack* allocations) {
Mathieu Chartier46a23632012-08-07 18:44:40 -0700417 Runtime* runtime = Runtime::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700418 // The callbacks check
419 // !is_marked where is_marked is the callback but we want
420 // !IsMarked && IsLive
421 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
422 // Or for swapped (IsLive || !IsMarked).
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700423
424 ArrayMarkedCheck visitor;
425 visitor.live_stack = allocations;
426 visitor.mark_sweep = this;
427 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedArrayCallback, &visitor);
428 runtime->GetMonitorList()->SweepMonitorList(IsMarkedArrayCallback, &visitor);
429 SweepJniWeakGlobals(IsMarkedArrayCallback, &visitor);
430}
431
432void MarkSweep::SweepSystemWeaks() {
433 Runtime* runtime = Runtime::Current();
434 // The callbacks check
435 // !is_marked where is_marked is the callback but we want
436 // !IsMarked && IsLive
437 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
438 // Or for swapped (IsLive || !IsMarked).
439 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedCallback, this);
440 runtime->GetMonitorList()->SweepMonitorList(IsMarkedCallback, this);
441 SweepJniWeakGlobals(IsMarkedCallback, this);
Carl Shapiro58551df2011-07-24 03:09:51 -0700442}
443
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700444bool MarkSweep::VerifyIsLiveCallback(const Object* obj, void* arg) {
445 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
446 // We don't actually want to sweep the object, so lets return "marked"
447 return true;
448}
449
450void MarkSweep::VerifyIsLive(const Object* obj) {
451 Heap* heap = GetHeap();
452 if (!heap->GetLiveBitmap()->Test(obj)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700453 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
454 if (!large_object_space->GetLiveObjects()->Test(obj)) {
455 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
456 heap->allocation_stack_->End()) {
457 // Object not found!
458 heap->DumpSpaces();
459 LOG(FATAL) << "Found dead object " << obj;
460 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700461 }
462 }
463}
464
465void MarkSweep::VerifySystemWeaks() {
466 Runtime* runtime = Runtime::Current();
467 // Verify system weaks, uses a special IsMarked callback which always returns true.
468 runtime->GetInternTable()->SweepInternTableWeaks(VerifyIsLiveCallback, this);
469 runtime->GetMonitorList()->SweepMonitorList(VerifyIsLiveCallback, this);
470
471 JavaVMExt* vm = runtime->GetJavaVM();
Ian Rogers50b35e22012-10-04 10:09:15 -0700472 MutexLock mu(Thread::Current(), vm->weak_globals_lock);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700473 IndirectReferenceTable* table = &vm->weak_globals;
474 typedef IndirectReferenceTable::iterator It; // TODO: C++0x auto
475 for (It it = table->begin(), end = table->end(); it != end; ++it) {
476 const Object** entry = *it;
477 VerifyIsLive(*entry);
478 }
479}
480
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800481struct SweepCallbackContext {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700482 MarkSweep* mark_sweep;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800483 AllocSpace* space;
Ian Rogers50b35e22012-10-04 10:09:15 -0700484 Thread* self;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800485};
486
Ian Rogers30fab402012-01-23 15:43:46 -0800487void MarkSweep::SweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Elliott Hughes307f75d2011-10-12 18:04:40 -0700488 size_t freed_objects = num_ptrs;
489 size_t freed_bytes = 0;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800490 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700491 MarkSweep* mark_sweep = context->mark_sweep;
492 Heap* heap = mark_sweep->GetHeap();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800493 AllocSpace* space = context->space;
Ian Rogers50b35e22012-10-04 10:09:15 -0700494 Thread* self = context->self;
495 Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
Ian Rogers5d76c432011-10-31 21:42:49 -0700496 // Use a bulk free, that merges consecutive objects before freeing or free per object?
497 // Documentation suggests better free performance with merging, but this may be at the expensive
498 // of allocation.
499 // TODO: investigate performance
Ian Rogers30fab402012-01-23 15:43:46 -0800500 static const bool kUseFreeList = true;
501 if (kUseFreeList) {
Ian Rogers5d76c432011-10-31 21:42:49 -0700502 for (size_t i = 0; i < num_ptrs; ++i) {
503 Object* obj = static_cast<Object*>(ptrs[i]);
Ian Rogers30fab402012-01-23 15:43:46 -0800504 freed_bytes += space->AllocationSize(obj);
Ian Rogers5d76c432011-10-31 21:42:49 -0700505 }
Ian Rogers30fab402012-01-23 15:43:46 -0800506 // AllocSpace::FreeList clears the value in ptrs, so perform after clearing the live bit
Ian Rogers50b35e22012-10-04 10:09:15 -0700507 space->FreeList(self, num_ptrs, ptrs);
Ian Rogers5d76c432011-10-31 21:42:49 -0700508 } else {
509 for (size_t i = 0; i < num_ptrs; ++i) {
510 Object* obj = static_cast<Object*>(ptrs[i]);
Ian Rogers30fab402012-01-23 15:43:46 -0800511 freed_bytes += space->AllocationSize(obj);
Ian Rogers50b35e22012-10-04 10:09:15 -0700512 space->Free(self, obj);
Ian Rogers5d76c432011-10-31 21:42:49 -0700513 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700514 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700515
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700516 heap->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700517 mark_sweep->freed_objects_ += freed_objects;
518 mark_sweep->freed_bytes_ += freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700519}
520
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700521void MarkSweep::ZygoteSweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700522 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Ian Rogers50b35e22012-10-04 10:09:15 -0700523 Locks::heap_bitmap_lock_->AssertExclusiveHeld(context->self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700524 Heap* heap = context->mark_sweep->GetHeap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700525 // We don't free any actual memory to avoid dirtying the shared zygote pages.
526 for (size_t i = 0; i < num_ptrs; ++i) {
527 Object* obj = static_cast<Object*>(ptrs[i]);
528 heap->GetLiveBitmap()->Clear(obj);
529 heap->GetCardTable()->MarkCard(obj);
530 }
531}
532
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700533void MarkSweep::SweepArray(TimingLogger& logger, ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700534 size_t freed_bytes = 0;
535 AllocSpace* space = heap_->GetAllocSpace();
Elliott Hughes2da50362011-10-10 16:57:08 -0700536
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700537 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
538 // bitmap, resulting in occasional frees of Weaks which are still in use.
539 // TODO: Fix when sweeping weaks works properly with mutators unpaused + allocation list.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700540 SweepSystemWeaksArray(allocations);
541 logger.AddSplit("SweepSystemWeaks");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700542
543 // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
544 // going to free.
545 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
546 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700547 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
548 SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
549 SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700550 if (swap_bitmaps) {
551 std::swap(live_bitmap, mark_bitmap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700552 std::swap(large_live_objects, large_mark_objects);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700553 }
554
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700555 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700556 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700557 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700558 Object** out = objects;
559
560 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -0700561 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700562 for (size_t i = 0;i < count;++i) {
563 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700564 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
565 if (LIKELY(mark_bitmap->HasAddress(obj))) {
566 if (!mark_bitmap->Test(obj)) {
567 // Don't bother un-marking since we clear the mark bitmap anyways.
568 *(out++) = obj;
569 size_t size = space->AllocationSize(obj);
570 freed_bytes += size;
571 }
572 } else if (!large_mark_objects->Test(obj)) {
573 ++freed_large_objects;
574 size_t size = large_object_space->AllocationSize(obj);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700575 freed_bytes += size;
Ian Rogers50b35e22012-10-04 10:09:15 -0700576 large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700577 }
578 }
579 logger.AddSplit("Process allocation stack");
580
581 size_t freed_objects = out - objects;
Mathieu Chartier40e978b2012-09-07 11:38:36 -0700582 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700583 << " objects with size " << PrettySize(freed_bytes);
Ian Rogers50b35e22012-10-04 10:09:15 -0700584 space->FreeList(self, freed_objects, objects);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700585 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes);
Mathieu Chartier40e978b2012-09-07 11:38:36 -0700586 freed_objects_ += freed_objects;
587 freed_bytes_ += freed_bytes;
588 logger.AddSplit("FreeList");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700589 allocations->Reset();
590 logger.AddSplit("Reset stack");
591}
592
593void MarkSweep::Sweep(bool partial, bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700594 DCHECK(mark_stack_->IsEmpty());
595
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700596 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
597 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700598 SweepSystemWeaks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700599
Mathieu Chartier46a23632012-08-07 18:44:40 -0700600 const Spaces& spaces = heap_->GetSpaces();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800601 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700602 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -0700603 scc.self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700604 // TODO: C++0x auto
605 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700606 ContinuousSpace* space = *it;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700607 if (
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700608 space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
609 (!partial && space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700610 ) {
611 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
612 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
613 scc.space = space->AsAllocSpace();
614 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
615 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700616 if (swap_bitmaps) {
617 std::swap(live_bitmap, mark_bitmap);
618 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700619 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700620 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700621 SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
622 &SweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700623 } else {
624 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual memory.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700625 SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
626 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700627 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700628 }
629 }
630}
631
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700632void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
633 // Sweep large objects
634 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700635 SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
636 SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
637 if (swap_bitmaps) {
638 std::swap(large_live_objects, large_mark_objects);
639 }
640 SpaceSetMap::Objects& live_objects = large_live_objects->GetObjects();
641 // O(n*log(n)) but hopefully there are not too many large objects.
642 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700643 size_t freed_bytes = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700644 // TODO: C++0x
Ian Rogers50b35e22012-10-04 10:09:15 -0700645 Thread* self = Thread::Current();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700646 for (SpaceSetMap::Objects::iterator it = live_objects.begin(); it != live_objects.end(); ++it) {
647 if (!large_mark_objects->Test(*it)) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700648 freed_bytes += large_object_space->AllocationSize(*it);
Ian Rogers50b35e22012-10-04 10:09:15 -0700649 large_object_space->Free(self, const_cast<Object*>(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700650 ++freed_objects;
651 }
652 }
653 freed_objects_ += freed_objects;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700654 freed_bytes_ += freed_bytes;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700655 // Large objects don't count towards bytes_allocated.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700656 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700657}
658
Carl Shapiro69759ea2011-07-21 18:13:35 -0700659// Scans instance fields.
Elliott Hughesb0663112011-10-19 18:16:37 -0700660inline void MarkSweep::ScanInstanceFields(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700661 DCHECK(obj != NULL);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700662 Class* klass = obj->GetClass();
663 DCHECK(klass != NULL);
Elliott Hughes2da50362011-10-10 16:57:08 -0700664 ScanFields(obj, klass->GetReferenceInstanceOffsets(), false);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700665}
666
667// Scans static storage on a Class.
Elliott Hughesb0663112011-10-19 18:16:37 -0700668inline void MarkSweep::ScanStaticFields(const Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700669 DCHECK(klass != NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700670 ScanFields(klass, klass->GetReferenceStaticOffsets(), true);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700671}
672
Elliott Hughesb0663112011-10-19 18:16:37 -0700673inline void MarkSweep::ScanFields(const Object* obj, uint32_t ref_offsets, bool is_static) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700674 if (ref_offsets != CLASS_WALK_SUPER) {
675 // Found a reference offset bitmap. Mark the specified offsets.
676 while (ref_offsets != 0) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700677 const size_t right_shift = CLZ(ref_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700678 MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
679 const Object* ref = obj->GetFieldObject<const Object*>(byte_offset, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700680 MarkObject(ref);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700681 ref_offsets ^= CLASS_HIGH_BIT >> right_shift;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700682 }
683 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700684 // There is no reference offset bitmap. In the non-static case,
685 // walk up the class inheritance hierarchy and find reference
686 // offsets the hard way. In the static case, just consider this
687 // class.
688 for (const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700689 klass != NULL;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700690 klass = is_static ? NULL : klass->GetSuperClass()) {
691 size_t num_reference_fields = (is_static
692 ? klass->NumReferenceStaticFields()
693 : klass->NumReferenceInstanceFields());
694 for (size_t i = 0; i < num_reference_fields; ++i) {
695 Field* field = (is_static
696 ? klass->GetStaticField(i)
697 : klass->GetInstanceField(i));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700698 MemberOffset field_offset = field->GetOffset();
699 const Object* ref = obj->GetFieldObject<const Object*>(field_offset, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700700 MarkObject(ref);
701 }
702 }
703 }
704}
705
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700706void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700707 const Spaces& spaces = heap_->GetSpaces();
708 // TODO: C++0x auto
709 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
710 if ((*cur)->IsAllocSpace() && (*cur)->Contains(ref)) {
711 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700712
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700713 bool is_marked = IsMarked(ref);
714 if (!is_marked) {
715 LOG(INFO) << **cur;
716 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
717 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
718 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
719 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700720
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700721 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
722 DCHECK(klass != NULL);
723 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
724 DCHECK(fields != NULL);
725 bool found = false;
726 for (int32_t i = 0; i < fields->GetLength(); ++i) {
727 const Field* cur = fields->Get(i);
728 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
729 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
730 found = true;
731 break;
732 }
733 }
734 if (!found) {
735 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
736 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700737
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700738 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
739 if (!obj_marked) {
740 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
741 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
742 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700743 }
744 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700745 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700746 break;
Ian Rogers5d76c432011-10-31 21:42:49 -0700747 }
748}
749
Carl Shapiro69759ea2011-07-21 18:13:35 -0700750// Scans the header, static field references, and interface pointers
751// of a class object.
Elliott Hughesb0663112011-10-19 18:16:37 -0700752inline void MarkSweep::ScanClass(const Object* obj) {
Elliott Hughes352a4242011-10-31 15:15:21 -0700753#ifndef NDEBUG
754 ++class_count_;
755#endif
Brian Carlstrom693267a2011-09-06 09:25:34 -0700756 ScanInstanceFields(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700757 ScanStaticFields(obj->AsClass());
Carl Shapiro69759ea2011-07-21 18:13:35 -0700758}
759
760// Scans the header of all array objects. If the array object is
761// specialized to a reference type, scans the array data as well.
Elliott Hughesb0663112011-10-19 18:16:37 -0700762inline void MarkSweep::ScanArray(const Object* obj) {
Elliott Hughes352a4242011-10-31 15:15:21 -0700763#ifndef NDEBUG
764 ++array_count_;
765#endif
Carl Shapiro69759ea2011-07-21 18:13:35 -0700766 MarkObject(obj->GetClass());
767 if (obj->IsObjectArray()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700768 const ObjectArray<Object>* array = obj->AsObjectArray<Object>();
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700769 for (int32_t i = 0; i < array->GetLength(); ++i) {
Ian Rogers5d76c432011-10-31 21:42:49 -0700770 const Object* element = array->GetWithoutChecks(i);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700771 MarkObject(element);
772 }
773 }
774}
775
Carl Shapiro69759ea2011-07-21 18:13:35 -0700776// Process the "referent" field in a java.lang.ref.Reference. If the
777// referent has not yet been marked, put it on the appropriate list in
778// the gcHeap for later processing.
779void MarkSweep::DelayReferenceReferent(Object* obj) {
780 DCHECK(obj != NULL);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700781 Class* klass = obj->GetClass();
782 DCHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700783 DCHECK(klass->IsReferenceClass());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800784 Object* pending = obj->GetFieldObject<Object*>(heap_->GetReferencePendingNextOffset(), false);
785 Object* referent = heap_->GetReferenceReferent(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700786 if (pending == NULL && referent != NULL && !IsMarked(referent)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700787 Object** list = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700788 if (klass->IsSoftReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700789 list = &soft_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700790 } else if (klass->IsWeakReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700791 list = &weak_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700792 } else if (klass->IsFinalizerReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700793 list = &finalizer_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700794 } else if (klass->IsPhantomReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700795 list = &phantom_reference_list_;
796 }
Brian Carlstrom0796af02011-10-12 14:31:45 -0700797 DCHECK(list != NULL) << PrettyClass(klass) << " " << std::hex << klass->GetAccessFlags();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800798 heap_->EnqueuePendingReference(obj, list);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700799 }
800}
801
802// Scans the header and field references of a data object. If the
803// scanned object is a reference subclass, it is scheduled for later
Elliott Hughesadb460d2011-10-05 17:02:34 -0700804// processing.
Elliott Hughesb0663112011-10-19 18:16:37 -0700805inline void MarkSweep::ScanOther(const Object* obj) {
Elliott Hughes352a4242011-10-31 15:15:21 -0700806#ifndef NDEBUG
807 ++other_count_;
808#endif
Carl Shapiro69759ea2011-07-21 18:13:35 -0700809 ScanInstanceFields(obj);
Elliott Hughes352a4242011-10-31 15:15:21 -0700810 if (obj->GetClass()->IsReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700811 DelayReferenceReferent(const_cast<Object*>(obj));
812 }
813}
814
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700815void MarkSweep::ScanRoot(const Object* obj) {
816 ScanObject(obj);
817}
818
Carl Shapiro69759ea2011-07-21 18:13:35 -0700819// Scans an object reference. Determines the type of the reference
820// and dispatches to a specialized scanning routine.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700821void MarkSweep::ScanObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700822 DCHECK(obj != NULL);
823 DCHECK(obj->GetClass() != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700824#ifndef NDEBUG
825 if (!IsMarked(obj)) {
826 heap_->DumpSpaces();
827 LOG(FATAL) << "Scanning unmarked object " << reinterpret_cast<const void*>(obj);
828 }
829#endif
Carl Shapiro69759ea2011-07-21 18:13:35 -0700830 if (obj->IsClass()) {
831 ScanClass(obj);
Brian Carlstromb63ec392011-08-27 17:38:27 -0700832 } else if (obj->IsArrayInstance()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700833 ScanArray(obj);
834 } else {
Carl Shapiro58551df2011-07-24 03:09:51 -0700835 ScanOther(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700836 }
837}
838
Ian Rogers5d76c432011-10-31 21:42:49 -0700839// Scan anything that's on the mark stack.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700840void MarkSweep::ProcessMarkStack() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700841 if (kUseMarkStackPrefetch) {
842 const size_t fifo_size = 4;
843 const size_t fifo_mask = fifo_size - 1;
844 const Object* fifo[fifo_size];
845 for (size_t i = 0;i < fifo_size;++i) {
846 fifo[i] = NULL;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700847 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700848 size_t fifo_pos = 0;
849 size_t fifo_count = 0;
850 for (;;) {
851 const Object* obj = fifo[fifo_pos & fifo_mask];
852 if (obj != NULL) {
853 ScanObject(obj);
854 fifo[fifo_pos & fifo_mask] = NULL;
855 --fifo_count;
856 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700857
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700858 if (!mark_stack_->IsEmpty()) {
859 const Object* obj = mark_stack_->PopBack();
860 DCHECK(obj != NULL);
861 fifo[fifo_pos & fifo_mask] = obj;
862 __builtin_prefetch(obj);
863 fifo_count++;
864 }
865 fifo_pos++;
866
867 if (!fifo_count) {
868 CHECK(mark_stack_->IsEmpty()) << mark_stack_->Size();
869 break;
870 }
871 }
872 } else {
873 while (!mark_stack_->IsEmpty()) {
874 const Object* obj = mark_stack_->PopBack();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700875 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700876 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700877 }
878 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700879}
880
Carl Shapiro69759ea2011-07-21 18:13:35 -0700881// Walks the reference list marking any references subject to the
882// reference clearing policy. References with a black referent are
883// removed from the list. References with white referents biased
884// toward saving are blackened and also removed from the list.
885void MarkSweep::PreserveSomeSoftReferences(Object** list) {
886 DCHECK(list != NULL);
887 Object* clear = NULL;
888 size_t counter = 0;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700889
890 DCHECK(mark_stack_->IsEmpty());
891
Carl Shapiro69759ea2011-07-21 18:13:35 -0700892 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800893 Object* ref = heap_->DequeuePendingReference(list);
894 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700895 if (referent == NULL) {
896 // Referent was cleared by the user during marking.
897 continue;
898 }
899 bool is_marked = IsMarked(referent);
900 if (!is_marked && ((++counter) & 1)) {
901 // Referent is white and biased toward saving, mark it.
902 MarkObject(referent);
903 is_marked = true;
904 }
905 if (!is_marked) {
906 // Referent is white, queue it for clearing.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800907 heap_->EnqueuePendingReference(ref, &clear);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700908 }
909 }
910 *list = clear;
911 // Restart the mark with the newly black references added to the
912 // root set.
913 ProcessMarkStack();
914}
915
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700916inline bool MarkSweep::IsMarked(const Object* object) const
917 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
918 if (object >= immune_begin_ && object < immune_end_) {
919 return true;
920 }
921 DCHECK(current_mark_bitmap_ != NULL);
922 if (current_mark_bitmap_->HasAddress(object)) {
923 return current_mark_bitmap_->Test(object);
924 }
925 return heap_->GetMarkBitmap()->Test(object);
926}
927
928
Carl Shapiro69759ea2011-07-21 18:13:35 -0700929// Unlink the reference list clearing references objects with white
930// referents. Cleared references registered to a reference queue are
931// scheduled for appending by the heap worker thread.
932void MarkSweep::ClearWhiteReferences(Object** list) {
933 DCHECK(list != NULL);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700934 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800935 Object* ref = heap_->DequeuePendingReference(list);
936 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700937 if (referent != NULL && !IsMarked(referent)) {
938 // Referent is white, clear it.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800939 heap_->ClearReferenceReferent(ref);
940 if (heap_->IsEnqueuable(ref)) {
941 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700942 }
943 }
944 }
945 DCHECK(*list == NULL);
946}
947
948// Enqueues finalizer references with white referents. White
949// referents are blackened, moved to the zombie field, and the
950// referent field is cleared.
951void MarkSweep::EnqueueFinalizerReferences(Object** list) {
952 DCHECK(list != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800953 MemberOffset zombie_offset = heap_->GetFinalizerReferenceZombieOffset();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700954 bool has_enqueued = false;
955 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800956 Object* ref = heap_->DequeuePendingReference(list);
957 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700958 if (referent != NULL && !IsMarked(referent)) {
959 MarkObject(referent);
960 // If the referent is non-null the reference must queuable.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800961 DCHECK(heap_->IsEnqueuable(ref));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700962 ref->SetFieldObject(zombie_offset, referent, false);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800963 heap_->ClearReferenceReferent(ref);
964 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700965 has_enqueued = true;
966 }
967 }
968 if (has_enqueued) {
969 ProcessMarkStack();
970 }
971 DCHECK(*list == NULL);
972}
973
Carl Shapiro58551df2011-07-24 03:09:51 -0700974// Process reference class instances and schedule finalizations.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700975void MarkSweep::ProcessReferences(Object** soft_references, bool clear_soft,
976 Object** weak_references,
977 Object** finalizer_references,
978 Object** phantom_references) {
979 DCHECK(soft_references != NULL);
980 DCHECK(weak_references != NULL);
981 DCHECK(finalizer_references != NULL);
982 DCHECK(phantom_references != NULL);
983
984 // Unless we are in the zygote or required to clear soft references
985 // with white references, preserve some white referents.
Ian Rogers2945e242012-06-03 14:45:16 -0700986 if (!clear_soft && !Runtime::Current()->IsZygote()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700987 PreserveSomeSoftReferences(soft_references);
988 }
989
990 // Clear all remaining soft and weak references with white
991 // referents.
992 ClearWhiteReferences(soft_references);
993 ClearWhiteReferences(weak_references);
994
995 // Preserve all white objects with finalize methods and schedule
996 // them for finalization.
997 EnqueueFinalizerReferences(finalizer_references);
998
999 // Clear all f-reachable soft and weak references with white
1000 // referents.
1001 ClearWhiteReferences(soft_references);
1002 ClearWhiteReferences(weak_references);
1003
1004 // Clear all phantom references with white referents.
1005 ClearWhiteReferences(phantom_references);
1006
1007 // At this point all reference lists should be empty.
1008 DCHECK(*soft_references == NULL);
1009 DCHECK(*weak_references == NULL);
1010 DCHECK(*finalizer_references == NULL);
1011 DCHECK(*phantom_references == NULL);
1012}
1013
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001014void MarkSweep::UnBindBitmaps() {
1015 const Spaces& spaces = heap_->GetSpaces();
1016 // TODO: C++0x auto
1017 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
1018 Space* space = *it;
1019 if (space->IsAllocSpace()) {
1020 AllocSpace* alloc_space = space->AsAllocSpace();
1021 if (alloc_space->temp_bitmap_.get() != NULL) {
1022 // At this point, the temp_bitmap holds our old mark bitmap.
1023 SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
1024 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1025 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1026 alloc_space->mark_bitmap_.reset(new_bitmap);
1027 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1028 }
1029 }
1030 }
1031}
1032
Carl Shapiro69759ea2011-07-21 18:13:35 -07001033MarkSweep::~MarkSweep() {
Elliott Hughes352a4242011-10-31 15:15:21 -07001034#ifndef NDEBUG
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001035 VLOG(heap) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_ << " other=" << other_count_;
Elliott Hughes352a4242011-10-31 15:15:21 -07001036#endif
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001037 // Ensure that the mark stack is empty.
1038 CHECK(mark_stack_->IsEmpty());
1039
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001040 // Clear all of the alloc spaces' mark bitmaps.
1041 const Spaces& spaces = heap_->GetSpaces();
1042 // TODO: C++0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001043 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001044 ContinuousSpace* space = *it;
1045 if (space->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1046 space->GetMarkBitmap()->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001047 }
1048 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001049 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001050
1051 // Reset the marked large objects.
1052 LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001053 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001054}
1055
1056} // namespace art