blob: 6e8dc7908a45e8b95572bd5463826c3f0050fec1 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 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 */
16
17#include "Dalvik.h"
Barry Hayeseac47ed2009-06-22 11:45:20 -070018#include "alloc/clz.h"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080019#include "alloc/HeapBitmap.h"
20#include "alloc/HeapInternal.h"
21#include "alloc/HeapSource.h"
22#include "alloc/MarkSweep.h"
23#include <limits.h> // for ULONG_MAX
24#include <sys/mman.h> // for madvise(), mmap()
25#include <cutils/ashmem.h>
The Android Open Source Project99409882009-03-18 22:20:24 -070026#include <errno.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080027
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080028#define GC_LOG_TAG LOG_TAG "-gc"
29
30#if LOG_NDEBUG
31#define LOGV_GC(...) ((void)0)
32#define LOGD_GC(...) ((void)0)
33#else
34#define LOGV_GC(...) LOG(LOG_VERBOSE, GC_LOG_TAG, __VA_ARGS__)
35#define LOGD_GC(...) LOG(LOG_DEBUG, GC_LOG_TAG, __VA_ARGS__)
36#endif
37
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080038#define LOGI_GC(...) LOG(LOG_INFO, GC_LOG_TAG, __VA_ARGS__)
39#define LOGW_GC(...) LOG(LOG_WARN, GC_LOG_TAG, __VA_ARGS__)
40#define LOGE_GC(...) LOG(LOG_ERROR, GC_LOG_TAG, __VA_ARGS__)
41
42#define LOG_SCAN(...) LOGV_GC("SCAN: " __VA_ARGS__)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080043
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080044#define ALIGN_UP_TO_PAGE_SIZE(p) \
Andy McFadden96516932009-10-28 17:39:02 -070045 (((size_t)(p) + (SYSTEM_PAGE_SIZE - 1)) & ~(SYSTEM_PAGE_SIZE - 1))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080046
47/* Do not cast the result of this to a boolean; the only set bit
48 * may be > 1<<8.
49 */
Carl Shapiro6343bd02010-02-16 17:40:19 -080050static inline long isMarked(const void *obj, const GcMarkContext *ctx)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080051{
Carl Shapirof373efd2010-02-19 00:46:33 -080052 return dvmHeapBitmapIsObjectBitSet(ctx->bitmap, obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080053}
54
55static bool
56createMarkStack(GcMarkStack *stack)
57{
58 const Object **limit;
59 size_t size;
The Android Open Source Project99409882009-03-18 22:20:24 -070060 int fd, err;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080061
62 /* Create a stack big enough for the worst possible case,
63 * where the heap is perfectly full of the smallest object.
64 * TODO: be better about memory usage; use a smaller stack with
65 * overflow detection and recovery.
66 */
67 size = dvmHeapSourceGetIdealFootprint() * sizeof(Object*) /
68 (sizeof(Object) + HEAP_SOURCE_CHUNK_OVERHEAD);
69 size = ALIGN_UP_TO_PAGE_SIZE(size);
70 fd = ashmem_create_region("dalvik-heap-markstack", size);
71 if (fd < 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -070072 LOGE_GC("Could not create %d-byte ashmem mark stack: %s\n",
73 size, strerror(errno));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080074 return false;
75 }
76 limit = (const Object **)mmap(NULL, size, PROT_READ | PROT_WRITE,
77 MAP_PRIVATE, fd, 0);
The Android Open Source Project99409882009-03-18 22:20:24 -070078 err = errno;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080079 close(fd);
80 if (limit == MAP_FAILED) {
The Android Open Source Project99409882009-03-18 22:20:24 -070081 LOGE_GC("Could not mmap %d-byte ashmem mark stack: %s\n",
82 size, strerror(err));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080083 return false;
84 }
85
86 memset(stack, 0, sizeof(*stack));
87 stack->limit = limit;
88 stack->base = (const Object **)((uintptr_t)limit + size);
89 stack->top = stack->base;
90
91 return true;
92}
93
94static void
95destroyMarkStack(GcMarkStack *stack)
96{
97 munmap((char *)stack->limit,
98 (uintptr_t)stack->base - (uintptr_t)stack->limit);
99 memset(stack, 0, sizeof(*stack));
100}
101
102#define MARK_STACK_PUSH(stack, obj) \
103 do { \
104 *--(stack).top = (obj); \
105 } while (false)
106
107bool
Carl Shapirod25566d2010-03-11 20:39:47 -0800108dvmHeapBeginMarkStep(GcMode mode)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800109{
110 GcMarkContext *mc = &gDvm.gcHeap->markContext;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800111
112 if (!createMarkStack(&mc->stack)) {
113 return false;
114 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800115 mc->finger = NULL;
Carl Shapirod25566d2010-03-11 20:39:47 -0800116 mc->immuneLimit = dvmHeapSourceGetImmuneLimit(mode);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800117 return true;
118}
119
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800120static long
Carl Shapiro6343bd02010-02-16 17:40:19 -0800121setAndReturnMarkBit(GcMarkContext *ctx, const void *obj)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800122{
Carl Shapirof373efd2010-02-19 00:46:33 -0800123 return dvmHeapBitmapSetAndReturnObjectBit(ctx->bitmap, obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800124}
125
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800126static void
Barry Hayese1bccb92010-05-18 09:48:37 -0700127markObjectNonNull(const Object *obj, GcMarkContext *ctx,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800128 bool checkFinger, bool forceStack)
129{
Barry Hayese1bccb92010-05-18 09:48:37 -0700130 assert(ctx != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800131 assert(obj != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800132 assert(dvmIsValidObject(obj));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800133
Carl Shapirob31b3012010-05-25 18:35:37 -0700134 if (obj < (Object *)ctx->immuneLimit) {
Carl Shapirod25566d2010-03-11 20:39:47 -0800135 assert(isMarked(obj, ctx));
136 return;
137 }
Carl Shapiro6343bd02010-02-16 17:40:19 -0800138 if (!setAndReturnMarkBit(ctx, obj)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800139 /* This object was not previously marked.
140 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800141 if (forceStack || (checkFinger && (void *)obj < ctx->finger)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800142 /* This object will need to go on the mark stack.
143 */
144 MARK_STACK_PUSH(ctx->stack, obj);
145 }
146
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800147#if WITH_HPROF
148 if (gDvm.gcHeap->hprofContext != NULL) {
149 hprofMarkRootObject(gDvm.gcHeap->hprofContext, obj, 0);
150 }
151#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800152 }
153}
154
155/* Used to mark objects when recursing. Recursion is done by moving
156 * the finger across the bitmaps in address order and marking child
157 * objects. Any newly-marked objects whose addresses are lower than
158 * the finger won't be visited by the bitmap scan, so those objects
159 * need to be added to the mark stack.
160 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700161static void markObject(const Object *obj, GcMarkContext *ctx)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800162{
Barry Hayese1bccb92010-05-18 09:48:37 -0700163 if (obj != NULL) {
164 markObjectNonNull(obj, ctx, true, false);
165 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800166}
167
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800168/* If the object hasn't already been marked, mark it and
169 * schedule it to be scanned for references.
170 *
171 * obj may not be NULL. The macro dvmMarkObject() should
172 * be used in situations where a reference may be NULL.
173 *
174 * This function may only be called when marking the root
Barry Hayese1bccb92010-05-18 09:48:37 -0700175 * set. When recursing, use the internal markObject().
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800176 */
177void
178dvmMarkObjectNonNull(const Object *obj)
179{
Barry Hayese1bccb92010-05-18 09:48:37 -0700180 assert(obj != NULL);
181 markObjectNonNull(obj, &gDvm.gcHeap->markContext, false, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800182}
183
184/* Mark the set of root objects.
185 *
186 * Things we need to scan:
187 * - System classes defined by root classloader
188 * - For each thread:
189 * - Interpreted stack, from top to "curFrame"
190 * - Dalvik registers (args + local vars)
191 * - JNI local references
192 * - Automatic VM local references (TrackedAlloc)
193 * - Associated Thread/VMThread object
194 * - ThreadGroups (could track & start with these instead of working
195 * upward from Threads)
196 * - Exception currently being thrown, if present
197 * - JNI global references
198 * - Interned string table
199 * - Primitive classes
200 * - Special objects
201 * - gDvm.outOfMemoryObj
202 * - Objects allocated with ALLOC_NO_GC
203 * - Objects pending finalization (but not yet finalized)
204 * - Objects in debugger object registry
205 *
206 * Don't need:
207 * - Native stack (for in-progress stuff in the VM)
208 * - The TrackedAlloc stuff watches all native VM references.
209 */
210void dvmHeapMarkRootSet()
211{
Barry Hayesd4f78d32010-06-08 09:34:42 -0700212 GcHeap *gcHeap = gDvm.gcHeap;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800213
214 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_STICKY_CLASS, 0);
215
Carl Shapirod25566d2010-03-11 20:39:47 -0800216 LOG_SCAN("immune objects");
Barry Hayes425848f2010-05-04 13:32:12 -0700217 dvmMarkImmuneObjects(gcHeap->markContext.immuneLimit);
Carl Shapirod25566d2010-03-11 20:39:47 -0800218
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800219 LOG_SCAN("root class loader\n");
220 dvmGcScanRootClassLoader();
221 LOG_SCAN("primitive classes\n");
222 dvmGcScanPrimitiveClasses();
223
224 /* dvmGcScanRootThreadGroups() sets a bunch of
225 * different scan states internally.
226 */
227 HPROF_CLEAR_GC_SCAN_STATE();
228
229 LOG_SCAN("root thread groups\n");
230 dvmGcScanRootThreadGroups();
231
232 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_INTERNED_STRING, 0);
233
234 LOG_SCAN("interned strings\n");
235 dvmGcScanInternedStrings();
236
237 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_GLOBAL, 0);
238
239 LOG_SCAN("JNI global refs\n");
240 dvmGcMarkJniGlobalRefs();
241
242 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_REFERENCE_CLEANUP, 0);
243
244 LOG_SCAN("pending reference operations\n");
Carl Shapiro646ba092010-06-10 15:17:00 -0700245 dvmHeapMarkLargeTableRefs(gcHeap->referenceOperations);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800246
247 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_FINALIZING, 0);
248
249 LOG_SCAN("pending finalizations\n");
Carl Shapiro646ba092010-06-10 15:17:00 -0700250 dvmHeapMarkLargeTableRefs(gcHeap->pendingFinalizationRefs);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800251
252 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_DEBUGGER, 0);
253
254 LOG_SCAN("debugger refs\n");
255 dvmGcMarkDebuggerRefs();
256
257 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_VM_INTERNAL, 0);
258
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800259 /* Mark any special objects we have sitting around.
260 */
261 LOG_SCAN("special objects\n");
262 dvmMarkObjectNonNull(gDvm.outOfMemoryObj);
263 dvmMarkObjectNonNull(gDvm.internalErrorObj);
Andy McFadden7fc3ce82009-07-14 15:57:23 -0700264 dvmMarkObjectNonNull(gDvm.noClassDefFoundErrorObj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800265//TODO: scan object references sitting in gDvm; use pointer begin & end
266
267 HPROF_CLEAR_GC_SCAN_STATE();
268}
269
270/*
Barry Hayese1bccb92010-05-18 09:48:37 -0700271 * Nothing past this point is allowed to use dvmMarkObject() or
272 * dvmMarkObjectNonNull(), which are for root-marking only.
273 * Scanning/recursion must use markObject(), which takes the finger
274 * into account.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800275 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700276#undef dvmMarkObject
277#define dvmMarkObject __dont_use_dvmMarkObject__
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800278#define dvmMarkObjectNonNull __dont_use_dvmMarkObjectNonNull__
279
Barry Hayese1bccb92010-05-18 09:48:37 -0700280/*
281 * Scans instance fields.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800282 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700283static void scanInstanceFields(const Object *obj, GcMarkContext *ctx)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800284{
Barry Hayese1bccb92010-05-18 09:48:37 -0700285 assert(obj != NULL);
286 assert(obj->clazz != NULL);
287 assert(ctx != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800288
Barry Hayese1bccb92010-05-18 09:48:37 -0700289 if (obj->clazz->refOffsets != CLASS_WALK_SUPER) {
290 unsigned int refOffsets = obj->clazz->refOffsets;
Barry Hayeseac47ed2009-06-22 11:45:20 -0700291 while (refOffsets != 0) {
292 const int rshift = CLZ(refOffsets);
293 refOffsets &= ~(CLASS_HIGH_BIT >> rshift);
294 markObject(dvmGetFieldObject((Object*)obj,
Barry Hayese1bccb92010-05-18 09:48:37 -0700295 CLASS_OFFSET_FROM_CLZ(rshift)), ctx);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800296 }
Barry Hayeseac47ed2009-06-22 11:45:20 -0700297 } else {
Barry Hayese1bccb92010-05-18 09:48:37 -0700298 ClassObject *clazz;
299 int i;
300 for (clazz = obj->clazz; clazz != NULL; clazz = clazz->super) {
301 InstField *field = clazz->ifields;
302 for (i = 0; i < clazz->ifieldRefCount; ++i, ++field) {
303 void *addr = BYTE_OFFSET((Object *)obj, field->byteOffset);
304 markObject(((JValue *)addr)->l, ctx);
Barry Hayeseac47ed2009-06-22 11:45:20 -0700305 }
Barry Hayeseac47ed2009-06-22 11:45:20 -0700306 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800307 }
308}
309
Barry Hayese1bccb92010-05-18 09:48:37 -0700310/*
311 * Scans the header, static field references, and interface
312 * pointers of a class object.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800313 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700314static void scanClassObject(const ClassObject *obj, GcMarkContext *ctx)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800315{
Barry Hayese1bccb92010-05-18 09:48:37 -0700316 int i;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800317
Barry Hayese1bccb92010-05-18 09:48:37 -0700318 assert(obj != NULL);
319 assert(obj->obj.clazz == gDvm.classJavaLangClass);
320 assert(ctx != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800321
Barry Hayese1bccb92010-05-18 09:48:37 -0700322 markObject((Object *)obj->obj.clazz, ctx);
323 if (IS_CLASS_FLAG_SET(obj, CLASS_ISARRAY)) {
324 markObject((Object *)obj->elementClass, ctx);
325 }
Barry Hayesc49db852010-05-14 13:43:34 -0700326 /* Do super and the interfaces contain Objects and not dex idx values? */
327 if (obj->status > CLASS_IDX) {
328 markObject((Object *)obj->super, ctx);
329 }
Barry Hayese1bccb92010-05-18 09:48:37 -0700330 markObject(obj->classLoader, ctx);
331 /* Scan static field references. */
332 for (i = 0; i < obj->sfieldCount; ++i) {
333 char ch = obj->sfields[i].field.signature[0];
334 if (ch == '[' || ch == 'L') {
335 markObject(obj->sfields[i].value.l, ctx);
336 }
337 }
338 /* Scan the instance fields. */
339 scanInstanceFields((const Object *)obj, ctx);
340 /* Scan interface references. */
Barry Hayesc49db852010-05-14 13:43:34 -0700341 if (obj->status > CLASS_IDX) {
342 for (i = 0; i < obj->interfaceCount; ++i) {
343 markObject((Object *)obj->interfaces[i], ctx);
344 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800345 }
346}
347
Barry Hayese1bccb92010-05-18 09:48:37 -0700348/*
349 * Scans the header of all array objects. If the array object is
350 * specialized to a reference type, scans the array data as well.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800351 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700352static void scanArrayObject(const ArrayObject *obj, GcMarkContext *ctx)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800353{
Barry Hayese1bccb92010-05-18 09:48:37 -0700354 size_t i;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800355
Barry Hayese1bccb92010-05-18 09:48:37 -0700356 assert(obj != NULL);
357 assert(obj->obj.clazz != NULL);
358 assert(ctx != NULL);
359 /* Scan the class object reference. */
360 markObject((Object *)obj->obj.clazz, ctx);
361 if (IS_CLASS_FLAG_SET(obj->obj.clazz, CLASS_ISOBJECTARRAY)) {
362 /* Scan the array contents. */
363 Object **contents = (Object **)obj->contents;
364 for (i = 0; i < obj->length; ++i) {
365 markObject(contents[i], ctx);
366 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800367 }
Barry Hayese1bccb92010-05-18 09:48:37 -0700368}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800369
Barry Hayese1bccb92010-05-18 09:48:37 -0700370/*
371 * Process the "referent" field in a java.lang.ref.Reference. If the
372 * referent has not yet been marked, put it on the appropriate list in
373 * the gcHeap for later processing.
374 */
375static void delayReferenceReferent(const DataObject *obj,
376 GcMarkContext *ctx)
377{
378 assert(obj != NULL);
379 assert(obj->obj.clazz != NULL);
380 assert(ctx != NULL);
381
382 GcHeap *gcHeap = gDvm.gcHeap;
383 Object *referent;
384
385 /* It's a subclass of java/lang/ref/Reference.
386 * The fields in this class have been arranged
387 * such that scanInstanceFields() did not actually
388 * mark the "referent" field; we need to handle
389 * it specially.
390 *
391 * If the referent already has a strong mark (isMarked(referent)),
392 * we don't care about its reference status.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800393 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700394 referent = dvmGetFieldObject((Object *)obj,
395 gDvm.offJavaLangRefReference_referent);
396 if (referent != NULL && !isMarked(referent, ctx))
397 {
398 u4 refFlags;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800399
Barry Hayese1bccb92010-05-18 09:48:37 -0700400 /* Find out what kind of reference is pointing
401 * to referent.
402 */
403 refFlags = GET_CLASS_FLAG_GROUP(obj->obj.clazz,
404 CLASS_ISREFERENCE |
405 CLASS_ISWEAKREFERENCE |
406 CLASS_ISPHANTOMREFERENCE);
407
408 /* We use the vmData field of Reference objects
409 * as a next pointer in a singly-linked list.
410 * That way, we don't need to allocate any memory
411 * while we're doing a GC.
412 */
413#define ADD_REF_TO_LIST(list, ref) \
414 do { \
415 Object *ARTL_ref_ = (/*de-const*/Object *)(ref); \
416 dvmSetFieldObject(ARTL_ref_, \
417 gDvm.offJavaLangRefReference_vmData, list); \
418 list = ARTL_ref_; \
419 } while (false)
420
421 /* At this stage, we just keep track of all of
422 * the live references that we've seen. Later,
423 * we'll walk through each of these lists and
424 * deal with the referents.
425 */
426 if (refFlags == CLASS_ISREFERENCE) {
427 /* It's a soft reference. Depending on the state,
428 * we'll attempt to collect all of them, some of
429 * them, or none of them.
430 */
431 ADD_REF_TO_LIST(gcHeap->softReferences, obj);
432 } else {
433 /* It's a weak or phantom reference.
434 * Clearing CLASS_ISREFERENCE will reveal which.
435 */
436 refFlags &= ~CLASS_ISREFERENCE;
437 if (refFlags == CLASS_ISWEAKREFERENCE) {
438 ADD_REF_TO_LIST(gcHeap->weakReferences, obj);
439 } else if (refFlags == CLASS_ISPHANTOMREFERENCE) {
440 ADD_REF_TO_LIST(gcHeap->phantomReferences, obj);
441 } else {
442 assert(!"Unknown reference type");
443 }
444 }
445#undef ADD_REF_TO_LIST
446 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800447}
448
Barry Hayese1bccb92010-05-18 09:48:37 -0700449/*
450 * Scans the header and field references of a data object.
451 */
452static void scanDataObject(const DataObject *obj, GcMarkContext *ctx)
453{
454 assert(obj != NULL);
455 assert(obj->obj.clazz != NULL);
456 assert(ctx != NULL);
457 /* Scan the class object. */
458 markObject((Object *)obj->obj.clazz, ctx);
459 /* Scan the instance fields. */
460 scanInstanceFields((const Object *)obj, ctx);
461
462 if (IS_CLASS_FLAG_SET(obj->obj.clazz, CLASS_ISREFERENCE)) {
463 delayReferenceReferent(obj, ctx);
464 }
465}
466
467/*
468 * Scans an object reference. Determines the type of the reference
469 * and dispatches to a specialized scanning routine.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800470 */
471static void scanObject(const Object *obj, GcMarkContext *ctx)
472{
Barry Hayese1bccb92010-05-18 09:48:37 -0700473 assert(obj != NULL);
474 assert(ctx != NULL);
Barry Hayes899cdb72010-06-08 09:59:12 -0700475 assert(obj->clazz != NULL);
Carl Shapiro1a8e21a2010-06-08 13:19:57 -0700476#if WITH_HPROF
477 if (gDvm.gcHeap->hprofContext != NULL) {
478 hprofDumpHeapObject(gDvm.gcHeap->hprofContext, obj);
479 }
480#endif
Barry Hayese1bccb92010-05-18 09:48:37 -0700481 /* Dispatch a type-specific scan routine. */
Carl Shapiro1a8e21a2010-06-08 13:19:57 -0700482 if (obj->clazz == gDvm.classJavaLangClass) {
Barry Hayese1bccb92010-05-18 09:48:37 -0700483 scanClassObject((ClassObject *)obj, ctx);
Carl Shapiro1a8e21a2010-06-08 13:19:57 -0700484 } else if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
Barry Hayes899cdb72010-06-08 09:59:12 -0700485 scanArrayObject((ArrayObject *)obj, ctx);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800486 } else {
Barry Hayes899cdb72010-06-08 09:59:12 -0700487 scanDataObject((DataObject *)obj, ctx);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800488 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800489}
490
491static void
492processMarkStack(GcMarkContext *ctx)
493{
494 const Object **const base = ctx->stack.base;
495
496 /* Scan anything that's on the mark stack.
497 * We can't use the bitmaps anymore, so use
498 * a finger that points past the end of them.
499 */
500 ctx->finger = (void *)ULONG_MAX;
501 while (ctx->stack.top != base) {
502 scanObject(*ctx->stack.top++, ctx);
503 }
504}
505
506#ifndef NDEBUG
507static uintptr_t gLastFinger = 0;
508#endif
509
510static bool
511scanBitmapCallback(size_t numPtrs, void **ptrs, const void *finger, void *arg)
512{
513 GcMarkContext *ctx = (GcMarkContext *)arg;
514 size_t i;
515
516#ifndef NDEBUG
517 assert((uintptr_t)finger >= gLastFinger);
518 gLastFinger = (uintptr_t)finger;
519#endif
520
521 ctx->finger = finger;
522 for (i = 0; i < numPtrs; i++) {
Carl Shapiro6343bd02010-02-16 17:40:19 -0800523 scanObject(*ptrs++, ctx);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800524 }
525
526 return true;
527}
528
529/* Given bitmaps with the root set marked, find and mark all
530 * reachable objects. When this returns, the entire set of
531 * live objects will be marked and the mark stack will be empty.
532 */
Carl Shapiro29540742010-03-26 15:34:39 -0700533void dvmHeapScanMarkedObjects(void)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800534{
535 GcMarkContext *ctx = &gDvm.gcHeap->markContext;
536
537 assert(ctx->finger == NULL);
538
539 /* The bitmaps currently have bits set for the root set.
540 * Walk across the bitmaps and scan each object.
541 */
542#ifndef NDEBUG
543 gLastFinger = 0;
544#endif
Carl Shapirof373efd2010-02-19 00:46:33 -0800545 dvmHeapBitmapWalk(ctx->bitmap, scanBitmapCallback, ctx);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800546
547 /* We've walked the mark bitmaps. Scan anything that's
548 * left on the mark stack.
549 */
550 processMarkStack(ctx);
551
552 LOG_SCAN("done with marked objects\n");
553}
554
Barry Hayes6930a112009-12-22 11:01:38 -0800555/** Clear the referent field.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800556 */
Barry Hayes6930a112009-12-22 11:01:38 -0800557static void clearReference(Object *reference)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800558{
559 /* This is what the default implementation of Reference.clear()
560 * does. We're required to clear all references to a given
561 * referent atomically, so we can't pop in and out of interp
562 * code each time.
563 *
Barry Hayes6930a112009-12-22 11:01:38 -0800564 * We don't ever actaully call overriding implementations of
565 * Reference.clear().
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800566 */
567 dvmSetFieldObject(reference,
568 gDvm.offJavaLangRefReference_referent, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800569}
570
Carl Shapiro29540742010-03-26 15:34:39 -0700571/*
572 * Returns true if the reference was registered with a reference queue
573 * and has not yet been enqueued.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800574 */
Carl Shapiro29540742010-03-26 15:34:39 -0700575static bool isEnqueuable(const Object *reference)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800576{
Barry Hayes6930a112009-12-22 11:01:38 -0800577 Object *queue = dvmGetFieldObject(reference,
578 gDvm.offJavaLangRefReference_queue);
579 Object *queueNext = dvmGetFieldObject(reference,
580 gDvm.offJavaLangRefReference_queueNext);
581 if (queue == NULL || queueNext != NULL) {
582 /* There is no queue, or the reference has already
583 * been enqueued. The Reference.enqueue() method
584 * will do nothing even if we call it.
585 */
586 return false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800587 }
588
589 /* We need to call enqueue(), but if we called it from
590 * here we'd probably deadlock. Schedule a call.
591 */
592 return true;
593}
594
Carl Shapiro29540742010-03-26 15:34:39 -0700595/*
596 * Schedules a reference to be appended to its reference queue.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800597 */
Carl Shapiro29540742010-03-26 15:34:39 -0700598static void enqueueReference(Object *ref)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800599{
Carl Shapiro646ba092010-06-10 15:17:00 -0700600 assert(ref != NULL);
Carl Shapiro29540742010-03-26 15:34:39 -0700601 assert(dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queue) != NULL);
602 assert(dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queueNext) == NULL);
Carl Shapiro646ba092010-06-10 15:17:00 -0700603 if (!dvmHeapAddRefToLargeTable(&gDvm.gcHeap->referenceOperations, ref)) {
Carl Shapiro29540742010-03-26 15:34:39 -0700604 LOGE_HEAP("enqueueReference(): no room for any more "
605 "reference operations\n");
606 dvmAbort();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800607 }
608}
609
Carl Shapiro29540742010-03-26 15:34:39 -0700610/*
611 * Walks the reference list marking any references subject to the
612 * reference clearing policy. References with a black referent are
613 * removed from the list. References with white referents biased
614 * toward saving are blackened and also removed from the list.
615 */
616void dvmHandleSoftRefs(Object **list)
617{
618 GcMarkContext *markContext;
619 Object *ref, *referent;
620 Object *prev, *next;
621 size_t referentOffset, vmDataOffset;
622 unsigned counter;
623 bool marked;
624
625 markContext = &gDvm.gcHeap->markContext;
626 vmDataOffset = gDvm.offJavaLangRefReference_vmData;
627 referentOffset = gDvm.offJavaLangRefReference_referent;
628 counter = 0;
629 prev = next = NULL;
630 ref = *list;
631 while (ref != NULL) {
632 referent = dvmGetFieldObject(ref, referentOffset);
633 next = dvmGetFieldObject(ref, vmDataOffset);
634 assert(referent != NULL);
635 marked = isMarked(referent, markContext);
636 if (!marked && ((++counter) & 1)) {
637 /* Referent is white and biased toward saving, mark it. */
Barry Hayese1bccb92010-05-18 09:48:37 -0700638 assert(referent != NULL);
639 markObject(referent, markContext);
Carl Shapiro29540742010-03-26 15:34:39 -0700640 marked = true;
641 }
642 if (marked) {
643 /* Referent is black, unlink it. */
644 if (prev != NULL) {
645 dvmSetFieldObject(ref, vmDataOffset, NULL);
646 dvmSetFieldObject(prev, vmDataOffset, next);
647 }
648 } else {
649 /* Referent is white, skip over it. */
650 prev = ref;
651 }
652 ref = next;
653 }
654 /*
655 * Restart the mark with the newly black references added to the
656 * root set.
657 */
658 processMarkStack(markContext);
659}
660
661/*
662 * Walks the reference list and clears references with an unmarked
663 * (white) referents. Cleared references registered to a reference
664 * queue are scheduled for appending by the heap worker thread.
665 */
666void dvmClearWhiteRefs(Object **list)
667{
668 GcMarkContext *markContext;
669 Object *ref, *referent;
670 size_t referentOffset, vmDataOffset;
671 bool doSignal;
672
673 markContext = &gDvm.gcHeap->markContext;
674 vmDataOffset = gDvm.offJavaLangRefReference_vmData;
675 referentOffset = gDvm.offJavaLangRefReference_referent;
676 doSignal = false;
677 while (*list != NULL) {
678 ref = *list;
679 referent = dvmGetFieldObject(ref, referentOffset);
680 *list = dvmGetFieldObject(ref, vmDataOffset);
681 assert(referent != NULL);
682 if (!isMarked(referent, markContext)) {
683 /* Referent is "white", clear it. */
684 clearReference(ref);
685 if (isEnqueuable(ref)) {
686 enqueueReference(ref);
687 doSignal = true;
688 }
689 }
690 }
691 /*
692 * If we cleared a reference with a reference queue we must notify
693 * the heap worker to append the reference.
694 */
695 if (doSignal) {
696 dvmSignalHeapWorker(false);
697 }
698 assert(*list == NULL);
699}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800700
701/* Find unreachable objects that need to be finalized,
702 * and schedule them for finalization.
703 */
704void dvmHeapScheduleFinalizations()
705{
706 HeapRefTable newPendingRefs;
707 LargeHeapRefTable *finRefs = gDvm.gcHeap->finalizableRefs;
708 Object **ref;
709 Object **lastRef;
710 size_t totalPendCount;
711 GcMarkContext *markContext = &gDvm.gcHeap->markContext;
712
713 /*
714 * All reachable objects have been marked.
715 * Any unmarked finalizable objects need to be finalized.
716 */
717
718 /* Create a table that the new pending refs will
719 * be added to.
720 */
Barry Hayesd4f78d32010-06-08 09:34:42 -0700721 if (!dvmHeapInitHeapRefTable(&newPendingRefs)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800722 //TODO: mark all finalizable refs and hope that
723 // we can schedule them next time. Watch out,
724 // because we may be expecting to free up space
725 // by calling finalizers.
726 LOGE_GC("dvmHeapScheduleFinalizations(): no room for "
727 "pending finalizations\n");
728 dvmAbort();
729 }
730
731 /* Walk through finalizableRefs and move any unmarked references
732 * to the list of new pending refs.
733 */
734 totalPendCount = 0;
735 while (finRefs != NULL) {
736 Object **gapRef;
737 size_t newPendCount = 0;
738
739 gapRef = ref = finRefs->refs.table;
740 lastRef = finRefs->refs.nextEntry;
741 while (ref < lastRef) {
Carl Shapiro6343bd02010-02-16 17:40:19 -0800742 if (!isMarked(*ref, markContext)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800743 if (!dvmHeapAddToHeapRefTable(&newPendingRefs, *ref)) {
744 //TODO: add the current table and allocate
745 // a new, smaller one.
746 LOGE_GC("dvmHeapScheduleFinalizations(): "
747 "no room for any more pending finalizations: %zd\n",
748 dvmHeapNumHeapRefTableEntries(&newPendingRefs));
749 dvmAbort();
750 }
751 newPendCount++;
752 } else {
753 /* This ref is marked, so will remain on finalizableRefs.
754 */
755 if (newPendCount > 0) {
756 /* Copy it up to fill the holes.
757 */
758 *gapRef++ = *ref;
759 } else {
760 /* No holes yet; don't bother copying.
761 */
762 gapRef++;
763 }
764 }
765 ref++;
766 }
767 finRefs->refs.nextEntry = gapRef;
768 //TODO: if the table is empty when we're done, free it.
769 totalPendCount += newPendCount;
770 finRefs = finRefs->next;
771 }
772 LOGD_GC("dvmHeapScheduleFinalizations(): %zd finalizers triggered.\n",
773 totalPendCount);
774 if (totalPendCount == 0) {
775 /* No objects required finalization.
776 * Free the empty temporary table.
777 */
778 dvmClearReferenceTable(&newPendingRefs);
779 return;
780 }
781
782 /* Add the new pending refs to the main list.
783 */
784 if (!dvmHeapAddTableToLargeTable(&gDvm.gcHeap->pendingFinalizationRefs,
785 &newPendingRefs))
786 {
787 LOGE_GC("dvmHeapScheduleFinalizations(): can't insert new "
788 "pending finalizations\n");
789 dvmAbort();
790 }
791
792 //TODO: try compacting the main list with a memcpy loop
793
794 /* Mark the refs we just moved; we don't want them or their
795 * children to get swept yet.
796 */
797 ref = newPendingRefs.table;
798 lastRef = newPendingRefs.nextEntry;
799 assert(ref < lastRef);
800 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_FINALIZING, 0);
801 while (ref < lastRef) {
Barry Hayese1bccb92010-05-18 09:48:37 -0700802 assert(*ref != NULL);
803 markObject(*ref, markContext);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800804 ref++;
805 }
806 HPROF_CLEAR_GC_SCAN_STATE();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800807 processMarkStack(markContext);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800808 dvmSignalHeapWorker(false);
809}
810
811void dvmHeapFinishMarkStep()
812{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800813 GcMarkContext *markContext;
814
815 markContext = &gDvm.gcHeap->markContext;
816
817 /* The sweep step freed every object that appeared in the
818 * HeapSource bitmaps that didn't appear in the mark bitmaps.
819 * The new state of the HeapSource is exactly the final
820 * mark bitmaps, so swap them in.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800821 */
Carl Shapirof373efd2010-02-19 00:46:33 -0800822 dvmHeapSourceSwapBitmaps();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800823
Carl Shapirof373efd2010-02-19 00:46:33 -0800824 /* Clean up everything else associated with the marking process.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800825 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800826 destroyMarkStack(&markContext->stack);
827
Carl Shapirof373efd2010-02-19 00:46:33 -0800828 markContext->finger = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800829}
830
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800831static bool
832sweepBitmapCallback(size_t numPtrs, void **ptrs, const void *finger, void *arg)
833{
834 const ClassObject *const classJavaLangClass = gDvm.classJavaLangClass;
Barry Hayes5cbb2302010-02-02 14:07:37 -0800835 const bool overwriteFree = gDvm.overwriteFree;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800836 size_t i;
Barry Hayesdde8ab02009-05-20 12:10:36 -0700837 void **origPtrs = ptrs;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800838
839 for (i = 0; i < numPtrs; i++) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800840 Object *obj;
841
Carl Shapiro6343bd02010-02-16 17:40:19 -0800842 obj = (Object *)*ptrs++;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800843
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800844 /* This assumes that java.lang.Class will never go away.
845 * If it can, and we were the last reference to it, it
846 * could have already been swept. However, even in that case,
847 * gDvm.classJavaLangClass should still have a useful
848 * value.
849 */
850 if (obj->clazz == classJavaLangClass) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800851 /* dvmFreeClassInnards() may have already been called,
852 * but it's safe to call on the same ClassObject twice.
853 */
854 dvmFreeClassInnards((ClassObject *)obj);
855 }
856
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800857 /* Overwrite the to-be-freed object to make stale references
858 * more obvious.
859 */
Barry Hayes5cbb2302010-02-02 14:07:37 -0800860 if (overwriteFree) {
Barry Hayes2e3c3e12010-02-22 09:39:10 -0800861 int objlen;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800862 ClassObject *clazz = obj->clazz;
Barry Hayes2e3c3e12010-02-22 09:39:10 -0800863 objlen = dvmHeapSourceChunkSize(obj);
864 memset(obj, 0xa5, objlen);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800865 obj->clazz = (ClassObject *)((uintptr_t)clazz ^ 0xffffffff);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800866 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800867 }
Barry Hayesdde8ab02009-05-20 12:10:36 -0700868 // TODO: dvmHeapSourceFreeList has a loop, just like the above
869 // does. Consider collapsing the two loops to save overhead.
870 dvmHeapSourceFreeList(numPtrs, origPtrs);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800871
872 return true;
873}
874
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800875/* Returns true if the given object is unmarked. Ignores the low bits
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800876 * of the pointer because the intern table may set them.
877 */
878static int isUnmarkedObject(void *object)
879{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800880 return !isMarked((void *)((uintptr_t)object & ~(HB_OBJECT_ALIGNMENT-1)),
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800881 &gDvm.gcHeap->markContext);
882}
883
884/* Walk through the list of objects that haven't been
885 * marked and free them.
886 */
887void
Carl Shapirod25566d2010-03-11 20:39:47 -0800888dvmHeapSweepUnmarkedObjects(GcMode mode, int *numFreed, size_t *sizeFreed)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800889{
Carl Shapirof373efd2010-02-19 00:46:33 -0800890 HeapBitmap markBits[HEAP_SOURCE_MAX_HEAP_COUNT];
Carl Shapirod77f7fd2010-04-05 19:23:31 -0700891 HeapBitmap liveBits[HEAP_SOURCE_MAX_HEAP_COUNT];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800892 size_t origObjectsAllocated;
893 size_t origBytesAllocated;
Carl Shapirod25566d2010-03-11 20:39:47 -0800894 size_t numBitmaps, numSweepBitmaps;
Barry Hayese168ebd2010-05-07 09:19:46 -0700895 size_t i;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800896
897 /* All reachable objects have been marked.
898 * Detach any unreachable interned strings before
899 * we sweep.
900 */
901 dvmGcDetachDeadInternedStrings(isUnmarkedObject);
902
903 /* Free any known objects that are not marked.
904 */
905 origObjectsAllocated = dvmHeapSourceGetValue(HS_OBJECTS_ALLOCATED, NULL, 0);
906 origBytesAllocated = dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
907
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800908 dvmSweepMonitorList(&gDvm.monitorList, isUnmarkedObject);
909
Carl Shapirof373efd2010-02-19 00:46:33 -0800910 numBitmaps = dvmHeapSourceGetNumHeaps();
Carl Shapirod77f7fd2010-04-05 19:23:31 -0700911 dvmHeapSourceGetObjectBitmaps(liveBits, markBits, numBitmaps);
Carl Shapirod25566d2010-03-11 20:39:47 -0800912 if (mode == GC_PARTIAL) {
913 numSweepBitmaps = 1;
Carl Shapirod77f7fd2010-04-05 19:23:31 -0700914 assert((uintptr_t)gDvm.gcHeap->markContext.immuneLimit == liveBits[0].base);
Carl Shapirod25566d2010-03-11 20:39:47 -0800915 } else {
916 numSweepBitmaps = numBitmaps;
917 }
Barry Hayese168ebd2010-05-07 09:19:46 -0700918 for (i = 0; i < numSweepBitmaps; i++) {
919 dvmHeapBitmapXorWalk(&markBits[i], &liveBits[i],
920 sweepBitmapCallback, NULL);
921 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800922
923 *numFreed = origObjectsAllocated -
924 dvmHeapSourceGetValue(HS_OBJECTS_ALLOCATED, NULL, 0);
925 *sizeFreed = origBytesAllocated -
926 dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
927
928#ifdef WITH_PROFILER
929 if (gDvm.allocProf.enabled) {
930 gDvm.allocProf.freeCount += *numFreed;
931 gDvm.allocProf.freeSize += *sizeFreed;
932 }
933#endif
934}