blob: 3ba54fc25f6420dba5ac1a004cda6404d563dc1a [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"
Carl Shapiroec805ea2010-06-28 16:28:26 -070023#include "alloc/Visit.h"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080024#include <limits.h> // for ULONG_MAX
25#include <sys/mman.h> // for madvise(), mmap()
26#include <cutils/ashmem.h>
The Android Open Source Project99409882009-03-18 22:20:24 -070027#include <errno.h>
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080028
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080029#define GC_LOG_TAG LOG_TAG "-gc"
30
31#if LOG_NDEBUG
32#define LOGV_GC(...) ((void)0)
33#define LOGD_GC(...) ((void)0)
34#else
35#define LOGV_GC(...) LOG(LOG_VERBOSE, GC_LOG_TAG, __VA_ARGS__)
36#define LOGD_GC(...) LOG(LOG_DEBUG, GC_LOG_TAG, __VA_ARGS__)
37#endif
38
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080039#define LOGI_GC(...) LOG(LOG_INFO, GC_LOG_TAG, __VA_ARGS__)
40#define LOGW_GC(...) LOG(LOG_WARN, GC_LOG_TAG, __VA_ARGS__)
41#define LOGE_GC(...) LOG(LOG_ERROR, GC_LOG_TAG, __VA_ARGS__)
42
43#define LOG_SCAN(...) LOGV_GC("SCAN: " __VA_ARGS__)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080044
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080045#define ALIGN_UP_TO_PAGE_SIZE(p) \
Andy McFadden96516932009-10-28 17:39:02 -070046 (((size_t)(p) + (SYSTEM_PAGE_SIZE - 1)) & ~(SYSTEM_PAGE_SIZE - 1))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080047
48/* Do not cast the result of this to a boolean; the only set bit
49 * may be > 1<<8.
50 */
Carl Shapiro6343bd02010-02-16 17:40:19 -080051static inline long isMarked(const void *obj, const GcMarkContext *ctx)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080052{
Carl Shapirof373efd2010-02-19 00:46:33 -080053 return dvmHeapBitmapIsObjectBitSet(ctx->bitmap, obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080054}
55
56static bool
57createMarkStack(GcMarkStack *stack)
58{
59 const Object **limit;
60 size_t size;
The Android Open Source Project99409882009-03-18 22:20:24 -070061 int fd, err;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080062
63 /* Create a stack big enough for the worst possible case,
64 * where the heap is perfectly full of the smallest object.
65 * TODO: be better about memory usage; use a smaller stack with
66 * overflow detection and recovery.
67 */
68 size = dvmHeapSourceGetIdealFootprint() * sizeof(Object*) /
69 (sizeof(Object) + HEAP_SOURCE_CHUNK_OVERHEAD);
70 size = ALIGN_UP_TO_PAGE_SIZE(size);
71 fd = ashmem_create_region("dalvik-heap-markstack", size);
72 if (fd < 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -070073 LOGE_GC("Could not create %d-byte ashmem mark stack: %s\n",
74 size, strerror(errno));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080075 return false;
76 }
77 limit = (const Object **)mmap(NULL, size, PROT_READ | PROT_WRITE,
78 MAP_PRIVATE, fd, 0);
The Android Open Source Project99409882009-03-18 22:20:24 -070079 err = errno;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080080 close(fd);
81 if (limit == MAP_FAILED) {
The Android Open Source Project99409882009-03-18 22:20:24 -070082 LOGE_GC("Could not mmap %d-byte ashmem mark stack: %s\n",
83 size, strerror(err));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080084 return false;
85 }
86
87 memset(stack, 0, sizeof(*stack));
88 stack->limit = limit;
89 stack->base = (const Object **)((uintptr_t)limit + size);
90 stack->top = stack->base;
91
92 return true;
93}
94
95static void
96destroyMarkStack(GcMarkStack *stack)
97{
98 munmap((char *)stack->limit,
99 (uintptr_t)stack->base - (uintptr_t)stack->limit);
100 memset(stack, 0, sizeof(*stack));
101}
102
103#define MARK_STACK_PUSH(stack, obj) \
104 do { \
105 *--(stack).top = (obj); \
106 } while (false)
107
108bool
Carl Shapirod25566d2010-03-11 20:39:47 -0800109dvmHeapBeginMarkStep(GcMode mode)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800110{
111 GcMarkContext *mc = &gDvm.gcHeap->markContext;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800112
113 if (!createMarkStack(&mc->stack)) {
114 return false;
115 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800116 mc->finger = NULL;
Carl Shapirod25566d2010-03-11 20:39:47 -0800117 mc->immuneLimit = dvmHeapSourceGetImmuneLimit(mode);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800118 return true;
119}
120
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800121static long
Carl Shapiro6343bd02010-02-16 17:40:19 -0800122setAndReturnMarkBit(GcMarkContext *ctx, const void *obj)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800123{
Carl Shapirof373efd2010-02-19 00:46:33 -0800124 return dvmHeapBitmapSetAndReturnObjectBit(ctx->bitmap, obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800125}
126
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800127static void
Barry Hayese1bccb92010-05-18 09:48:37 -0700128markObjectNonNull(const Object *obj, GcMarkContext *ctx,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800129 bool checkFinger, bool forceStack)
130{
Barry Hayese1bccb92010-05-18 09:48:37 -0700131 assert(ctx != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800132 assert(obj != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800133 assert(dvmIsValidObject(obj));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800134
Carl Shapirob31b3012010-05-25 18:35:37 -0700135 if (obj < (Object *)ctx->immuneLimit) {
Carl Shapirod25566d2010-03-11 20:39:47 -0800136 assert(isMarked(obj, ctx));
137 return;
138 }
Carl Shapiro6343bd02010-02-16 17:40:19 -0800139 if (!setAndReturnMarkBit(ctx, obj)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800140 /* This object was not previously marked.
141 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800142 if (forceStack || (checkFinger && (void *)obj < ctx->finger)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800143 /* This object will need to go on the mark stack.
144 */
145 MARK_STACK_PUSH(ctx->stack, obj);
146 }
147
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800148#if WITH_HPROF
149 if (gDvm.gcHeap->hprofContext != NULL) {
150 hprofMarkRootObject(gDvm.gcHeap->hprofContext, obj, 0);
151 }
152#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800153 }
154}
155
156/* Used to mark objects when recursing. Recursion is done by moving
157 * the finger across the bitmaps in address order and marking child
158 * objects. Any newly-marked objects whose addresses are lower than
159 * the finger won't be visited by the bitmap scan, so those objects
160 * need to be added to the mark stack.
161 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700162static void markObject(const Object *obj, GcMarkContext *ctx)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800163{
Barry Hayese1bccb92010-05-18 09:48:37 -0700164 if (obj != NULL) {
165 markObjectNonNull(obj, ctx, true, false);
166 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800167}
168
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800169/* If the object hasn't already been marked, mark it and
170 * schedule it to be scanned for references.
171 *
172 * obj may not be NULL. The macro dvmMarkObject() should
173 * be used in situations where a reference may be NULL.
174 *
175 * This function may only be called when marking the root
Barry Hayese1bccb92010-05-18 09:48:37 -0700176 * set. When recursing, use the internal markObject().
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800177 */
178void
179dvmMarkObjectNonNull(const Object *obj)
180{
Barry Hayese1bccb92010-05-18 09:48:37 -0700181 assert(obj != NULL);
182 markObjectNonNull(obj, &gDvm.gcHeap->markContext, false, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800183}
184
185/* Mark the set of root objects.
186 *
187 * Things we need to scan:
188 * - System classes defined by root classloader
189 * - For each thread:
190 * - Interpreted stack, from top to "curFrame"
191 * - Dalvik registers (args + local vars)
192 * - JNI local references
193 * - Automatic VM local references (TrackedAlloc)
194 * - Associated Thread/VMThread object
195 * - ThreadGroups (could track & start with these instead of working
196 * upward from Threads)
197 * - Exception currently being thrown, if present
198 * - JNI global references
199 * - Interned string table
200 * - Primitive classes
201 * - Special objects
202 * - gDvm.outOfMemoryObj
203 * - Objects allocated with ALLOC_NO_GC
204 * - Objects pending finalization (but not yet finalized)
205 * - Objects in debugger object registry
206 *
207 * Don't need:
208 * - Native stack (for in-progress stuff in the VM)
209 * - The TrackedAlloc stuff watches all native VM references.
210 */
211void dvmHeapMarkRootSet()
212{
Barry Hayesd4f78d32010-06-08 09:34:42 -0700213 GcHeap *gcHeap = gDvm.gcHeap;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800214
215 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_STICKY_CLASS, 0);
216
Carl Shapirod25566d2010-03-11 20:39:47 -0800217 LOG_SCAN("immune objects");
Barry Hayes425848f2010-05-04 13:32:12 -0700218 dvmMarkImmuneObjects(gcHeap->markContext.immuneLimit);
Carl Shapirod25566d2010-03-11 20:39:47 -0800219
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800220 LOG_SCAN("root class loader\n");
221 dvmGcScanRootClassLoader();
222 LOG_SCAN("primitive classes\n");
223 dvmGcScanPrimitiveClasses();
224
225 /* dvmGcScanRootThreadGroups() sets a bunch of
226 * different scan states internally.
227 */
228 HPROF_CLEAR_GC_SCAN_STATE();
229
230 LOG_SCAN("root thread groups\n");
231 dvmGcScanRootThreadGroups();
232
233 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_INTERNED_STRING, 0);
234
235 LOG_SCAN("interned strings\n");
236 dvmGcScanInternedStrings();
237
238 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_GLOBAL, 0);
239
240 LOG_SCAN("JNI global refs\n");
241 dvmGcMarkJniGlobalRefs();
242
243 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_REFERENCE_CLEANUP, 0);
244
245 LOG_SCAN("pending reference operations\n");
Carl Shapiro646ba092010-06-10 15:17:00 -0700246 dvmHeapMarkLargeTableRefs(gcHeap->referenceOperations);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800247
248 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_FINALIZING, 0);
249
250 LOG_SCAN("pending finalizations\n");
Carl Shapiro646ba092010-06-10 15:17:00 -0700251 dvmHeapMarkLargeTableRefs(gcHeap->pendingFinalizationRefs);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800252
253 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_DEBUGGER, 0);
254
255 LOG_SCAN("debugger refs\n");
256 dvmGcMarkDebuggerRefs();
257
258 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_VM_INTERNAL, 0);
259
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800260 /* Mark any special objects we have sitting around.
261 */
262 LOG_SCAN("special objects\n");
263 dvmMarkObjectNonNull(gDvm.outOfMemoryObj);
264 dvmMarkObjectNonNull(gDvm.internalErrorObj);
Andy McFadden7fc3ce82009-07-14 15:57:23 -0700265 dvmMarkObjectNonNull(gDvm.noClassDefFoundErrorObj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800266//TODO: scan object references sitting in gDvm; use pointer begin & end
267
268 HPROF_CLEAR_GC_SCAN_STATE();
269}
270
271/*
Barry Hayese1bccb92010-05-18 09:48:37 -0700272 * Nothing past this point is allowed to use dvmMarkObject() or
273 * dvmMarkObjectNonNull(), which are for root-marking only.
274 * Scanning/recursion must use markObject(), which takes the finger
275 * into account.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800276 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700277#undef dvmMarkObject
278#define dvmMarkObject __dont_use_dvmMarkObject__
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800279#define dvmMarkObjectNonNull __dont_use_dvmMarkObjectNonNull__
280
Barry Hayese1bccb92010-05-18 09:48:37 -0700281/*
282 * Scans instance fields.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800283 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700284static void scanInstanceFields(const Object *obj, GcMarkContext *ctx)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800285{
Barry Hayese1bccb92010-05-18 09:48:37 -0700286 assert(obj != NULL);
287 assert(obj->clazz != NULL);
288 assert(ctx != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800289
Barry Hayese1bccb92010-05-18 09:48:37 -0700290 if (obj->clazz->refOffsets != CLASS_WALK_SUPER) {
291 unsigned int refOffsets = obj->clazz->refOffsets;
Barry Hayeseac47ed2009-06-22 11:45:20 -0700292 while (refOffsets != 0) {
293 const int rshift = CLZ(refOffsets);
294 refOffsets &= ~(CLASS_HIGH_BIT >> rshift);
295 markObject(dvmGetFieldObject((Object*)obj,
Barry Hayese1bccb92010-05-18 09:48:37 -0700296 CLASS_OFFSET_FROM_CLZ(rshift)), ctx);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800297 }
Barry Hayeseac47ed2009-06-22 11:45:20 -0700298 } else {
Barry Hayese1bccb92010-05-18 09:48:37 -0700299 ClassObject *clazz;
300 int i;
301 for (clazz = obj->clazz; clazz != NULL; clazz = clazz->super) {
302 InstField *field = clazz->ifields;
303 for (i = 0; i < clazz->ifieldRefCount; ++i, ++field) {
304 void *addr = BYTE_OFFSET((Object *)obj, field->byteOffset);
305 markObject(((JValue *)addr)->l, ctx);
Barry Hayeseac47ed2009-06-22 11:45:20 -0700306 }
Barry Hayeseac47ed2009-06-22 11:45:20 -0700307 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800308 }
309}
310
Barry Hayese1bccb92010-05-18 09:48:37 -0700311/*
312 * Scans the header, static field references, and interface
313 * pointers of a class object.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800314 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700315static void scanClassObject(const ClassObject *obj, GcMarkContext *ctx)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800316{
Barry Hayese1bccb92010-05-18 09:48:37 -0700317 int i;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800318
Barry Hayese1bccb92010-05-18 09:48:37 -0700319 assert(obj != NULL);
320 assert(obj->obj.clazz == gDvm.classJavaLangClass);
321 assert(ctx != NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800322
Barry Hayese1bccb92010-05-18 09:48:37 -0700323 markObject((Object *)obj->obj.clazz, ctx);
324 if (IS_CLASS_FLAG_SET(obj, CLASS_ISARRAY)) {
325 markObject((Object *)obj->elementClass, ctx);
326 }
Barry Hayesc49db852010-05-14 13:43:34 -0700327 /* Do super and the interfaces contain Objects and not dex idx values? */
328 if (obj->status > CLASS_IDX) {
329 markObject((Object *)obj->super, ctx);
330 }
Barry Hayese1bccb92010-05-18 09:48:37 -0700331 markObject(obj->classLoader, ctx);
332 /* Scan static field references. */
333 for (i = 0; i < obj->sfieldCount; ++i) {
334 char ch = obj->sfields[i].field.signature[0];
335 if (ch == '[' || ch == 'L') {
336 markObject(obj->sfields[i].value.l, ctx);
337 }
338 }
339 /* Scan the instance fields. */
340 scanInstanceFields((const Object *)obj, ctx);
341 /* Scan interface references. */
Barry Hayesc49db852010-05-14 13:43:34 -0700342 if (obj->status > CLASS_IDX) {
343 for (i = 0; i < obj->interfaceCount; ++i) {
344 markObject((Object *)obj->interfaces[i], ctx);
345 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800346 }
347}
348
Barry Hayese1bccb92010-05-18 09:48:37 -0700349/*
350 * Scans the header of all array objects. If the array object is
351 * specialized to a reference type, scans the array data as well.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800352 */
Barry Hayese1bccb92010-05-18 09:48:37 -0700353static void scanArrayObject(const ArrayObject *obj, GcMarkContext *ctx)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800354{
Barry Hayese1bccb92010-05-18 09:48:37 -0700355 size_t i;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800356
Barry Hayese1bccb92010-05-18 09:48:37 -0700357 assert(obj != NULL);
358 assert(obj->obj.clazz != NULL);
359 assert(ctx != NULL);
360 /* Scan the class object reference. */
361 markObject((Object *)obj->obj.clazz, ctx);
362 if (IS_CLASS_FLAG_SET(obj->obj.clazz, CLASS_ISOBJECTARRAY)) {
363 /* Scan the array contents. */
364 Object **contents = (Object **)obj->contents;
365 for (i = 0; i < obj->length; ++i) {
366 markObject(contents[i], ctx);
367 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800368 }
Barry Hayese1bccb92010-05-18 09:48:37 -0700369}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800370
Barry Hayese1bccb92010-05-18 09:48:37 -0700371/*
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700372 * Returns class flags relating to Reference subclasses.
373 */
374static int referenceClassFlags(const Object *obj)
375{
376 int flags = CLASS_ISREFERENCE |
377 CLASS_ISWEAKREFERENCE |
378 CLASS_ISPHANTOMREFERENCE;
379 return GET_CLASS_FLAG_GROUP(obj->clazz, flags);
380}
381
382/*
383 * Returns true if the object derives from SoftReference.
384 */
385static bool isSoftReference(const Object *obj)
386{
387 return referenceClassFlags(obj) == CLASS_ISREFERENCE;
388}
389
390/*
391 * Returns true if the object derives from WeakReference.
392 */
393static bool isWeakReference(const Object *obj)
394{
395 return referenceClassFlags(obj) & CLASS_ISWEAKREFERENCE;
396}
397
398/*
399 * Returns true if the object derives from PhantomReference.
400 */
401static bool isPhantomReference(const Object *obj)
402{
403 return referenceClassFlags(obj) & CLASS_ISPHANTOMREFERENCE;
404}
405
406/*
407 * Adds a reference to the tail of a circular queue of references.
408 */
409static void enqueuePendingReference(Object *ref, Object **list)
410{
411 size_t offset;
412
413 assert(ref != NULL);
414 assert(list != NULL);
415 offset = gDvm.offJavaLangRefReference_pendingNext;
416 if (*list == NULL) {
417 dvmSetFieldObject(ref, offset, ref);
418 *list = ref;
419 } else {
420 Object *head = dvmGetFieldObject(*list, offset);
421 dvmSetFieldObject(ref, offset, head);
422 dvmSetFieldObject(*list, offset, ref);
423 }
424}
425
426/*
427 * Removes the reference at the head of circular queue of references.
428 */
429static Object *dequeuePendingReference(Object **list)
430{
431 Object *ref, *head;
432 size_t offset;
433
434 assert(list != NULL);
435 assert(*list != NULL);
436 offset = gDvm.offJavaLangRefReference_pendingNext;
437 head = dvmGetFieldObject(*list, offset);
438 if (*list == head) {
439 ref = *list;
440 *list = NULL;
441 } else {
442 Object *next = dvmGetFieldObject(head, offset);
443 dvmSetFieldObject(*list, offset, next);
444 ref = head;
445 }
446 dvmSetFieldObject(ref, offset, NULL);
447 return ref;
448}
449
450/*
Barry Hayese1bccb92010-05-18 09:48:37 -0700451 * Process the "referent" field in a java.lang.ref.Reference. If the
452 * referent has not yet been marked, put it on the appropriate list in
453 * the gcHeap for later processing.
454 */
Barry Hayes697b5a92010-06-23 11:38:52 -0700455static void delayReferenceReferent(Object *obj, GcMarkContext *ctx)
Barry Hayese1bccb92010-05-18 09:48:37 -0700456{
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700457 GcHeap *gcHeap = gDvm.gcHeap;
458 Object *pending, *referent;
459 size_t pendingNextOffset, referentOffset;
460
Barry Hayese1bccb92010-05-18 09:48:37 -0700461 assert(obj != NULL);
Barry Hayes697b5a92010-06-23 11:38:52 -0700462 assert(obj->clazz != NULL);
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700463 assert(IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISREFERENCE));
Barry Hayese1bccb92010-05-18 09:48:37 -0700464 assert(ctx != NULL);
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700465 pendingNextOffset = gDvm.offJavaLangRefReference_pendingNext;
466 referentOffset = gDvm.offJavaLangRefReference_referent;
467 pending = dvmGetFieldObject(obj, pendingNextOffset);
468 referent = dvmGetFieldObject(obj, referentOffset);
469 if (pending == NULL && referent != NULL && !isMarked(referent, ctx)) {
470 Object **list = NULL;
471 if (isSoftReference(obj)) {
472 list = &gcHeap->softReferences;
473 } else if (isWeakReference(obj)) {
474 list = &gcHeap->weakReferences;
475 } else if (isPhantomReference(obj)) {
476 list = &gcHeap->phantomReferences;
Barry Hayese1bccb92010-05-18 09:48:37 -0700477 }
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700478 assert(list != NULL);
479 enqueuePendingReference(obj, list);
Barry Hayese1bccb92010-05-18 09:48:37 -0700480 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800481}
482
Barry Hayese1bccb92010-05-18 09:48:37 -0700483/*
484 * Scans the header and field references of a data object.
485 */
Barry Hayes697b5a92010-06-23 11:38:52 -0700486static void scanDataObject(DataObject *obj, GcMarkContext *ctx)
Barry Hayese1bccb92010-05-18 09:48:37 -0700487{
488 assert(obj != NULL);
489 assert(obj->obj.clazz != NULL);
490 assert(ctx != NULL);
491 /* Scan the class object. */
492 markObject((Object *)obj->obj.clazz, ctx);
493 /* Scan the instance fields. */
494 scanInstanceFields((const Object *)obj, ctx);
Barry Hayese1bccb92010-05-18 09:48:37 -0700495 if (IS_CLASS_FLAG_SET(obj->obj.clazz, CLASS_ISREFERENCE)) {
Barry Hayes697b5a92010-06-23 11:38:52 -0700496 delayReferenceReferent((Object *)obj, ctx);
Barry Hayese1bccb92010-05-18 09:48:37 -0700497 }
498}
499
500/*
501 * Scans an object reference. Determines the type of the reference
502 * and dispatches to a specialized scanning routine.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800503 */
504static void scanObject(const Object *obj, GcMarkContext *ctx)
505{
Barry Hayese1bccb92010-05-18 09:48:37 -0700506 assert(obj != NULL);
507 assert(ctx != NULL);
Barry Hayes899cdb72010-06-08 09:59:12 -0700508 assert(obj->clazz != NULL);
Carl Shapiro1a8e21a2010-06-08 13:19:57 -0700509#if WITH_HPROF
510 if (gDvm.gcHeap->hprofContext != NULL) {
511 hprofDumpHeapObject(gDvm.gcHeap->hprofContext, obj);
512 }
513#endif
Barry Hayese1bccb92010-05-18 09:48:37 -0700514 /* Dispatch a type-specific scan routine. */
Carl Shapiro1a8e21a2010-06-08 13:19:57 -0700515 if (obj->clazz == gDvm.classJavaLangClass) {
Barry Hayese1bccb92010-05-18 09:48:37 -0700516 scanClassObject((ClassObject *)obj, ctx);
Carl Shapiro1a8e21a2010-06-08 13:19:57 -0700517 } else if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
Barry Hayes899cdb72010-06-08 09:59:12 -0700518 scanArrayObject((ArrayObject *)obj, ctx);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800519 } else {
Barry Hayes899cdb72010-06-08 09:59:12 -0700520 scanDataObject((DataObject *)obj, ctx);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800521 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800522}
523
Barry Hayes6e5cf602010-06-22 12:32:59 -0700524/*
525 * Variants for partial GC. Scan immune objects, and rebuild the card
526 * table.
527 */
528
529/*
530 * Mark an object which was found in an immune object.
531 */
532static void scanImmuneReference(const Object *obj, GcMarkContext *ctx)
533{
534 if (obj != NULL) {
535 if (obj < (Object *)ctx->immuneLimit) {
536 assert(isMarked(obj, ctx));
537 } else {
538 ctx->crossGen = true;
539 markObjectNonNull(obj, ctx, true, false);
540 }
541 }
542}
543
544/*
545 * Scans instance fields.
546 */
547static void scanImmuneInstanceFields(const Object *obj, GcMarkContext *ctx)
548{
549 assert(obj != NULL);
550 assert(obj->clazz != NULL);
551 assert(ctx != NULL);
552
553 if (obj->clazz->refOffsets != CLASS_WALK_SUPER) {
554 unsigned int refOffsets = obj->clazz->refOffsets;
555 while (refOffsets != 0) {
556 const int rshift = CLZ(refOffsets);
557 refOffsets &= ~(CLASS_HIGH_BIT >> rshift);
558 scanImmuneReference(
559 dvmGetFieldObject((Object*)obj, CLASS_OFFSET_FROM_CLZ(rshift)),
560 ctx);
561 }
562 } else {
563 ClassObject *clazz;
564 int i;
565 for (clazz = obj->clazz; clazz != NULL; clazz = clazz->super) {
566 InstField *field = clazz->ifields;
567 for (i = 0; i < clazz->ifieldRefCount; ++i, ++field) {
568 void *addr = BYTE_OFFSET((Object *)obj, field->byteOffset);
569 scanImmuneReference(((JValue *)addr)->l, ctx);
570 }
571 }
572 }
573}
574
575/*
576 * Scans the header, static field references, and interface
577 * pointers of a class object.
578 */
579static void scanImmuneClassObject(const ClassObject *obj, GcMarkContext *ctx)
580{
581 int i;
582
583 assert(obj != NULL);
584 assert(obj->obj.clazz == gDvm.classJavaLangClass);
585 assert(ctx != NULL);
586
587 scanImmuneReference((Object *)obj->obj.clazz, ctx);
588 if (IS_CLASS_FLAG_SET(obj, CLASS_ISARRAY)) {
589 scanImmuneReference((Object *)obj->elementClass, ctx);
590 }
591 /* Do super and the interfaces contain Objects and not dex idx values? */
592 if (obj->status > CLASS_IDX) {
593 scanImmuneReference((Object *)obj->super, ctx);
594 }
595 scanImmuneReference(obj->classLoader, ctx);
596 /* Scan static field references. */
597 for (i = 0; i < obj->sfieldCount; ++i) {
598 char ch = obj->sfields[i].field.signature[0];
599 if (ch == '[' || ch == 'L') {
600 scanImmuneReference(obj->sfields[i].value.l, ctx);
601 }
602 }
603 /* Scan the instance fields. */
604 scanImmuneInstanceFields((const Object *)obj, ctx);
605 /* Scan interface references. */
606 if (obj->status > CLASS_IDX) {
607 for (i = 0; i < obj->interfaceCount; ++i) {
608 scanImmuneReference((Object *)obj->interfaces[i], ctx);
609 }
610 }
611}
612
613/*
614 * Scans the header of all array objects. If the array object is
615 * specialized to a reference type, scans the array data as well.
616 */
617static void scanImmuneArrayObject(const ArrayObject *obj, GcMarkContext *ctx)
618{
619 size_t i;
620
621 assert(obj != NULL);
622 assert(obj->obj.clazz != NULL);
623 assert(ctx != NULL);
624 /* Scan the class object reference. */
625 scanImmuneReference((Object *)obj->obj.clazz, ctx);
626 if (IS_CLASS_FLAG_SET(obj->obj.clazz, CLASS_ISOBJECTARRAY)) {
627 /* Scan the array contents. */
628 Object **contents = (Object **)obj->contents;
629 for (i = 0; i < obj->length; ++i) {
630 scanImmuneReference(contents[i], ctx);
631 }
632 }
633}
634
635/*
636 * Scans the header and field references of a data object.
637 */
638static void scanImmuneDataObject(DataObject *obj, GcMarkContext *ctx)
639{
640 assert(obj != NULL);
641 assert(obj->obj.clazz != NULL);
642 assert(ctx != NULL);
643 /* Scan the class object. */
644 scanImmuneReference((Object *)obj->obj.clazz, ctx);
645 /* Scan the instance fields. */
646 scanImmuneInstanceFields((const Object *)obj, ctx);
647 if (IS_CLASS_FLAG_SET(obj->obj.clazz, CLASS_ISREFERENCE)) {
648 scanImmuneReference((Object *)obj, ctx);
649 }
650}
651
652/*
653 * Scans an object reference. Determines the type of the reference
654 * and dispatches to a specialized scanning routine.
655 */
656static void scanImmuneObject(const Object *obj, GcMarkContext *ctx)
657{
658 assert(obj != NULL);
659 assert(obj->clazz != NULL);
660 assert(ctx != NULL);
661 assert(obj < (Object *)ctx->immuneLimit);
662
663#if WITH_HPROF
664 if (gDvm.gcHeap->hprofContext != NULL) {
665 hprofDumpHeapObject(gDvm.gcHeap->hprofContext, obj);
666 }
667#endif
668 /* Dispatch a type-specific scan routine. */
669 if (obj->clazz == gDvm.classJavaLangClass) {
670 scanImmuneClassObject((ClassObject *)obj, ctx);
671 } else if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
672 scanImmuneArrayObject((ArrayObject *)obj, ctx);
673 } else {
674 scanImmuneDataObject((DataObject *)obj, ctx);
675 }
676}
677
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800678static void
679processMarkStack(GcMarkContext *ctx)
680{
681 const Object **const base = ctx->stack.base;
682
683 /* Scan anything that's on the mark stack.
684 * We can't use the bitmaps anymore, so use
685 * a finger that points past the end of them.
686 */
687 ctx->finger = (void *)ULONG_MAX;
688 while (ctx->stack.top != base) {
689 scanObject(*ctx->stack.top++, ctx);
690 }
691}
692
693#ifndef NDEBUG
694static uintptr_t gLastFinger = 0;
695#endif
696
697static bool
698scanBitmapCallback(size_t numPtrs, void **ptrs, const void *finger, void *arg)
699{
700 GcMarkContext *ctx = (GcMarkContext *)arg;
701 size_t i;
702
703#ifndef NDEBUG
704 assert((uintptr_t)finger >= gLastFinger);
705 gLastFinger = (uintptr_t)finger;
706#endif
707
708 ctx->finger = finger;
709 for (i = 0; i < numPtrs; i++) {
Carl Shapiro6343bd02010-02-16 17:40:19 -0800710 scanObject(*ptrs++, ctx);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800711 }
712
713 return true;
714}
715
716/* Given bitmaps with the root set marked, find and mark all
717 * reachable objects. When this returns, the entire set of
718 * live objects will be marked and the mark stack will be empty.
719 */
Carl Shapiro29540742010-03-26 15:34:39 -0700720void dvmHeapScanMarkedObjects(void)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800721{
722 GcMarkContext *ctx = &gDvm.gcHeap->markContext;
723
724 assert(ctx->finger == NULL);
725
726 /* The bitmaps currently have bits set for the root set.
727 * Walk across the bitmaps and scan each object.
728 */
729#ifndef NDEBUG
730 gLastFinger = 0;
731#endif
Barry Hayes6e5cf602010-06-22 12:32:59 -0700732 if (gDvm.executionMode == kExecutionModeInterpPortable) {
733 /* The portable interpreter dirties cards on write; other
734 * modes do not yet do so.
735 * TODO: Bring the fast interpreter and JIT into the fold.
736 */
737 HeapBitmap markBits[HEAP_SOURCE_MAX_HEAP_COUNT];
738 HeapBitmap liveBits[HEAP_SOURCE_MAX_HEAP_COUNT];
739 size_t numBitmaps, i;
740 numBitmaps = dvmHeapSourceGetNumHeaps();
741 dvmHeapSourceGetObjectBitmaps(liveBits, markBits, numBitmaps);
742 for (i = 0; i < numBitmaps; i++) {
743 /* The use of finger to tell visited from unvisited objects
744 * requires we walk the bitmaps from low to high
745 * addresses. This code assumes [and asserts] that the order
746 * of the heaps returned is the reverse of that.
747 */
748 size_t j = numBitmaps-1-i;
749 assert(j == 0 || (markBits[j].base < markBits[j-1].base));
750 if (markBits[j].base < (uintptr_t)ctx->immuneLimit) {
751 if (gDvm.verifyCardTable) {
752 dvmVerifyCardTable(&markBits[j], ctx->immuneLimit);
753 }
754 uintptr_t minAddr = markBits[j].base;
755 uintptr_t maxAddr = markBits[j].base +
756 HB_MAX_OFFSET(&markBits[j]);
757 u1 *minCard = dvmCardFromAddr((void *)minAddr);
758 u1 *maxCard = dvmCardFromAddr((void *)maxAddr);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800759
Barry Hayes6e5cf602010-06-22 12:32:59 -0700760 u1 *card;
Barry Hayes8f921a72010-07-09 12:53:49 -0700761 /* TODO: This double-loop should be made faster. In
762 * particular the inner loop could get in bed with the
763 * bitmap scanning routines.
Barry Hayes6e5cf602010-06-22 12:32:59 -0700764 */
765 for (card = minCard; card <= maxCard; card++) {
766 if (*card == GC_CARD_DIRTY) {
767 uintptr_t addr = (uintptr_t)dvmAddrFromCard(card);
768 uintptr_t endAddr = addr + GC_CARD_SIZE;
769 ctx->crossGen = false;
770 for ( ; addr < endAddr; addr += 8) {
771 if (dvmIsValidObject((void *)addr)) {
772 scanImmuneObject((void *)addr, ctx);
773 }
774 }
775 if (! ctx->crossGen) {
776 *card = GC_CARD_CLEAN;
777 }
778 }
779 }
780 if (gDvm.verifyCardTable) {
781 dvmVerifyCardTable(&markBits[j], ctx->immuneLimit);
782 }
783 } else {
784 dvmHeapBitmapWalk(&markBits[j], scanBitmapCallback, ctx);
785 }
786 }
787 } else {
788 dvmHeapBitmapWalk(ctx->bitmap, scanBitmapCallback, ctx);
789 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800790 /* We've walked the mark bitmaps. Scan anything that's
791 * left on the mark stack.
792 */
793 processMarkStack(ctx);
794
795 LOG_SCAN("done with marked objects\n");
796}
797
Carl Shapiroec805ea2010-06-28 16:28:26 -0700798static void dirtyObjectVisitor(void *ptr, void *arg)
799{
800 markObject(*(Object **)ptr, (GcMarkContext *)arg);
801}
802
803/*
804 * Callback applied to each gray object to blacken it.
805 */
806static bool dirtyObjectCallback(size_t numPtrs, void **ptrs,
807 const void *finger, void *arg)
808{
809 GcMarkContext *ctx;
810 size_t i;
811
812 ctx = (GcMarkContext *)arg;
813 for (i = 0; i < numPtrs; ++i) {
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700814 Object *obj = ptrs[i];
815 if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISREFERENCE)) {
816 scanDataObject((DataObject *)obj, ctx);
817 } else {
818 dvmVisitObject(dirtyObjectVisitor, obj, ctx);
819 }
Carl Shapiroec805ea2010-06-28 16:28:26 -0700820 }
821 return true;
822}
823
824/*
825 * Re-mark dirtied objects. Iterates through all blackened objects
826 * looking for references to white objects.
827 */
828void dvmMarkDirtyObjects(void)
829{
830 HeapBitmap markBits[HEAP_SOURCE_MAX_HEAP_COUNT];
831 HeapBitmap liveBits[HEAP_SOURCE_MAX_HEAP_COUNT];
832 GcMarkContext *ctx;
833 size_t numBitmaps;
834 size_t i;
835
836 ctx = &gDvm.gcHeap->markContext;
837 /*
Carl Shapirof5860332010-06-28 23:02:08 -0700838 * The finger must have been set to the maximum value to ensure
839 * that gray objects will be pushed onto the mark stack.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700840 */
841 assert(ctx->finger == (void *)ULONG_MAX);
842 numBitmaps = dvmHeapSourceGetNumHeaps();
843 dvmHeapSourceGetObjectBitmaps(liveBits, markBits, numBitmaps);
844 for (i = 0; i < numBitmaps; i++) {
845 dvmHeapBitmapWalk(&markBits[i], dirtyObjectCallback, ctx);
846 }
847 processMarkStack(ctx);
848}
849
Carl Shapiro34f51992010-07-09 17:55:41 -0700850/*
851 * Clear the referent field.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800852 */
Barry Hayes6930a112009-12-22 11:01:38 -0800853static void clearReference(Object *reference)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800854{
Carl Shapiro34f51992010-07-09 17:55:41 -0700855 size_t offset = gDvm.offJavaLangRefReference_referent;
856 dvmSetFieldObject(reference, offset, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800857}
858
Carl Shapiro29540742010-03-26 15:34:39 -0700859/*
860 * Returns true if the reference was registered with a reference queue
861 * and has not yet been enqueued.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800862 */
Carl Shapiro29540742010-03-26 15:34:39 -0700863static bool isEnqueuable(const Object *reference)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800864{
Barry Hayes6930a112009-12-22 11:01:38 -0800865 Object *queue = dvmGetFieldObject(reference,
866 gDvm.offJavaLangRefReference_queue);
867 Object *queueNext = dvmGetFieldObject(reference,
868 gDvm.offJavaLangRefReference_queueNext);
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700869 return queue != NULL && queueNext == NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800870}
871
Carl Shapiro29540742010-03-26 15:34:39 -0700872/*
873 * Schedules a reference to be appended to its reference queue.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800874 */
Carl Shapiro29540742010-03-26 15:34:39 -0700875static void enqueueReference(Object *ref)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800876{
Carl Shapiro646ba092010-06-10 15:17:00 -0700877 assert(ref != NULL);
Carl Shapiro29540742010-03-26 15:34:39 -0700878 assert(dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queue) != NULL);
879 assert(dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queueNext) == NULL);
Carl Shapiro646ba092010-06-10 15:17:00 -0700880 if (!dvmHeapAddRefToLargeTable(&gDvm.gcHeap->referenceOperations, ref)) {
Carl Shapiro29540742010-03-26 15:34:39 -0700881 LOGE_HEAP("enqueueReference(): no room for any more "
882 "reference operations\n");
883 dvmAbort();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800884 }
885}
886
Carl Shapiro29540742010-03-26 15:34:39 -0700887/*
888 * Walks the reference list marking any references subject to the
889 * reference clearing policy. References with a black referent are
890 * removed from the list. References with white referents biased
891 * toward saving are blackened and also removed from the list.
892 */
893void dvmHandleSoftRefs(Object **list)
894{
895 GcMarkContext *markContext;
896 Object *ref, *referent;
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700897 Object *clear;
898 size_t pendingNextOffset, referentOffset;
899 size_t counter;
Carl Shapiro29540742010-03-26 15:34:39 -0700900 bool marked;
901
902 markContext = &gDvm.gcHeap->markContext;
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700903 pendingNextOffset = gDvm.offJavaLangRefReference_pendingNext;
Carl Shapiro29540742010-03-26 15:34:39 -0700904 referentOffset = gDvm.offJavaLangRefReference_referent;
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700905 clear = NULL;
Carl Shapiro29540742010-03-26 15:34:39 -0700906 counter = 0;
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700907 while (*list != NULL) {
908 ref = dequeuePendingReference(list);
Carl Shapiro29540742010-03-26 15:34:39 -0700909 referent = dvmGetFieldObject(ref, referentOffset);
Carl Shapiro29540742010-03-26 15:34:39 -0700910 assert(referent != NULL);
911 marked = isMarked(referent, markContext);
912 if (!marked && ((++counter) & 1)) {
913 /* Referent is white and biased toward saving, mark it. */
Barry Hayese1bccb92010-05-18 09:48:37 -0700914 markObject(referent, markContext);
Carl Shapiro29540742010-03-26 15:34:39 -0700915 marked = true;
916 }
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700917 if (!marked) {
918 /* Referent is white, queue it for clearing. */
919 enqueuePendingReference(ref, &clear);
Carl Shapiro29540742010-03-26 15:34:39 -0700920 }
Carl Shapiro29540742010-03-26 15:34:39 -0700921 }
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700922 *list = clear;
Carl Shapiro29540742010-03-26 15:34:39 -0700923 /*
924 * Restart the mark with the newly black references added to the
925 * root set.
926 */
927 processMarkStack(markContext);
928}
929
930/*
931 * Walks the reference list and clears references with an unmarked
932 * (white) referents. Cleared references registered to a reference
933 * queue are scheduled for appending by the heap worker thread.
934 */
935void dvmClearWhiteRefs(Object **list)
936{
937 GcMarkContext *markContext;
938 Object *ref, *referent;
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700939 size_t pendingNextOffset, referentOffset;
Carl Shapiro29540742010-03-26 15:34:39 -0700940 bool doSignal;
941
942 markContext = &gDvm.gcHeap->markContext;
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700943 pendingNextOffset = gDvm.offJavaLangRefReference_pendingNext;
Carl Shapiro29540742010-03-26 15:34:39 -0700944 referentOffset = gDvm.offJavaLangRefReference_referent;
945 doSignal = false;
946 while (*list != NULL) {
Carl Shapiro2a6f4842010-07-09 16:50:54 -0700947 ref = dequeuePendingReference(list);
Carl Shapiro29540742010-03-26 15:34:39 -0700948 referent = dvmGetFieldObject(ref, referentOffset);
Carl Shapiro29540742010-03-26 15:34:39 -0700949 assert(referent != NULL);
950 if (!isMarked(referent, markContext)) {
951 /* Referent is "white", clear it. */
952 clearReference(ref);
953 if (isEnqueuable(ref)) {
954 enqueueReference(ref);
955 doSignal = true;
956 }
957 }
958 }
959 /*
960 * If we cleared a reference with a reference queue we must notify
961 * the heap worker to append the reference.
962 */
963 if (doSignal) {
964 dvmSignalHeapWorker(false);
965 }
966 assert(*list == NULL);
967}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800968
969/* Find unreachable objects that need to be finalized,
970 * and schedule them for finalization.
971 */
972void dvmHeapScheduleFinalizations()
973{
974 HeapRefTable newPendingRefs;
975 LargeHeapRefTable *finRefs = gDvm.gcHeap->finalizableRefs;
976 Object **ref;
977 Object **lastRef;
978 size_t totalPendCount;
979 GcMarkContext *markContext = &gDvm.gcHeap->markContext;
980
981 /*
982 * All reachable objects have been marked.
983 * Any unmarked finalizable objects need to be finalized.
984 */
985
986 /* Create a table that the new pending refs will
987 * be added to.
988 */
Barry Hayesd4f78d32010-06-08 09:34:42 -0700989 if (!dvmHeapInitHeapRefTable(&newPendingRefs)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800990 //TODO: mark all finalizable refs and hope that
991 // we can schedule them next time. Watch out,
992 // because we may be expecting to free up space
993 // by calling finalizers.
994 LOGE_GC("dvmHeapScheduleFinalizations(): no room for "
995 "pending finalizations\n");
996 dvmAbort();
997 }
998
999 /* Walk through finalizableRefs and move any unmarked references
1000 * to the list of new pending refs.
1001 */
1002 totalPendCount = 0;
1003 while (finRefs != NULL) {
1004 Object **gapRef;
1005 size_t newPendCount = 0;
1006
1007 gapRef = ref = finRefs->refs.table;
1008 lastRef = finRefs->refs.nextEntry;
1009 while (ref < lastRef) {
Carl Shapiro6343bd02010-02-16 17:40:19 -08001010 if (!isMarked(*ref, markContext)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001011 if (!dvmHeapAddToHeapRefTable(&newPendingRefs, *ref)) {
1012 //TODO: add the current table and allocate
1013 // a new, smaller one.
1014 LOGE_GC("dvmHeapScheduleFinalizations(): "
1015 "no room for any more pending finalizations: %zd\n",
1016 dvmHeapNumHeapRefTableEntries(&newPendingRefs));
1017 dvmAbort();
1018 }
1019 newPendCount++;
1020 } else {
1021 /* This ref is marked, so will remain on finalizableRefs.
1022 */
1023 if (newPendCount > 0) {
1024 /* Copy it up to fill the holes.
1025 */
1026 *gapRef++ = *ref;
1027 } else {
1028 /* No holes yet; don't bother copying.
1029 */
1030 gapRef++;
1031 }
1032 }
1033 ref++;
1034 }
1035 finRefs->refs.nextEntry = gapRef;
1036 //TODO: if the table is empty when we're done, free it.
1037 totalPendCount += newPendCount;
1038 finRefs = finRefs->next;
1039 }
1040 LOGD_GC("dvmHeapScheduleFinalizations(): %zd finalizers triggered.\n",
1041 totalPendCount);
1042 if (totalPendCount == 0) {
1043 /* No objects required finalization.
1044 * Free the empty temporary table.
1045 */
1046 dvmClearReferenceTable(&newPendingRefs);
1047 return;
1048 }
1049
1050 /* Add the new pending refs to the main list.
1051 */
1052 if (!dvmHeapAddTableToLargeTable(&gDvm.gcHeap->pendingFinalizationRefs,
1053 &newPendingRefs))
1054 {
1055 LOGE_GC("dvmHeapScheduleFinalizations(): can't insert new "
1056 "pending finalizations\n");
1057 dvmAbort();
1058 }
1059
1060 //TODO: try compacting the main list with a memcpy loop
1061
1062 /* Mark the refs we just moved; we don't want them or their
1063 * children to get swept yet.
1064 */
1065 ref = newPendingRefs.table;
1066 lastRef = newPendingRefs.nextEntry;
1067 assert(ref < lastRef);
1068 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_FINALIZING, 0);
1069 while (ref < lastRef) {
Barry Hayese1bccb92010-05-18 09:48:37 -07001070 assert(*ref != NULL);
1071 markObject(*ref, markContext);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001072 ref++;
1073 }
1074 HPROF_CLEAR_GC_SCAN_STATE();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001075 processMarkStack(markContext);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001076 dvmSignalHeapWorker(false);
1077}
1078
1079void dvmHeapFinishMarkStep()
1080{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001081 GcMarkContext *markContext;
1082
1083 markContext = &gDvm.gcHeap->markContext;
1084
1085 /* The sweep step freed every object that appeared in the
1086 * HeapSource bitmaps that didn't appear in the mark bitmaps.
1087 * The new state of the HeapSource is exactly the final
1088 * mark bitmaps, so swap them in.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001089 */
Carl Shapirof373efd2010-02-19 00:46:33 -08001090 dvmHeapSourceSwapBitmaps();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001091
Carl Shapirof373efd2010-02-19 00:46:33 -08001092 /* Clean up everything else associated with the marking process.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001093 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001094 destroyMarkStack(&markContext->stack);
1095
Carl Shapirof373efd2010-02-19 00:46:33 -08001096 markContext->finger = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001097}
1098
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001099static bool
1100sweepBitmapCallback(size_t numPtrs, void **ptrs, const void *finger, void *arg)
1101{
1102 const ClassObject *const classJavaLangClass = gDvm.classJavaLangClass;
Barry Hayes5cbb2302010-02-02 14:07:37 -08001103 const bool overwriteFree = gDvm.overwriteFree;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001104 size_t i;
Barry Hayesdde8ab02009-05-20 12:10:36 -07001105 void **origPtrs = ptrs;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001106
1107 for (i = 0; i < numPtrs; i++) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001108 Object *obj;
1109
Carl Shapiro6343bd02010-02-16 17:40:19 -08001110 obj = (Object *)*ptrs++;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001111
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001112 /* This assumes that java.lang.Class will never go away.
1113 * If it can, and we were the last reference to it, it
1114 * could have already been swept. However, even in that case,
1115 * gDvm.classJavaLangClass should still have a useful
1116 * value.
1117 */
1118 if (obj->clazz == classJavaLangClass) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001119 /* dvmFreeClassInnards() may have already been called,
1120 * but it's safe to call on the same ClassObject twice.
1121 */
1122 dvmFreeClassInnards((ClassObject *)obj);
1123 }
1124
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001125 /* Overwrite the to-be-freed object to make stale references
1126 * more obvious.
1127 */
Barry Hayes5cbb2302010-02-02 14:07:37 -08001128 if (overwriteFree) {
Barry Hayes2e3c3e12010-02-22 09:39:10 -08001129 int objlen;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001130 ClassObject *clazz = obj->clazz;
Barry Hayes2e3c3e12010-02-22 09:39:10 -08001131 objlen = dvmHeapSourceChunkSize(obj);
1132 memset(obj, 0xa5, objlen);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001133 obj->clazz = (ClassObject *)((uintptr_t)clazz ^ 0xffffffff);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001134 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001135 }
Barry Hayesdde8ab02009-05-20 12:10:36 -07001136 // TODO: dvmHeapSourceFreeList has a loop, just like the above
1137 // does. Consider collapsing the two loops to save overhead.
1138 dvmHeapSourceFreeList(numPtrs, origPtrs);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001139
1140 return true;
1141}
1142
Carl Shapiro5a6071b2010-01-07 21:35:50 -08001143/* Returns true if the given object is unmarked. Ignores the low bits
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001144 * of the pointer because the intern table may set them.
1145 */
1146static int isUnmarkedObject(void *object)
1147{
Carl Shapiro6343bd02010-02-16 17:40:19 -08001148 return !isMarked((void *)((uintptr_t)object & ~(HB_OBJECT_ALIGNMENT-1)),
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001149 &gDvm.gcHeap->markContext);
1150}
1151
1152/* Walk through the list of objects that haven't been
1153 * marked and free them.
1154 */
1155void
Carl Shapirod25566d2010-03-11 20:39:47 -08001156dvmHeapSweepUnmarkedObjects(GcMode mode, int *numFreed, size_t *sizeFreed)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001157{
Carl Shapirof373efd2010-02-19 00:46:33 -08001158 HeapBitmap markBits[HEAP_SOURCE_MAX_HEAP_COUNT];
Carl Shapirod77f7fd2010-04-05 19:23:31 -07001159 HeapBitmap liveBits[HEAP_SOURCE_MAX_HEAP_COUNT];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001160 size_t origObjectsAllocated;
1161 size_t origBytesAllocated;
Carl Shapirod25566d2010-03-11 20:39:47 -08001162 size_t numBitmaps, numSweepBitmaps;
Barry Hayese168ebd2010-05-07 09:19:46 -07001163 size_t i;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001164
1165 /* All reachable objects have been marked.
1166 * Detach any unreachable interned strings before
1167 * we sweep.
1168 */
1169 dvmGcDetachDeadInternedStrings(isUnmarkedObject);
1170
1171 /* Free any known objects that are not marked.
1172 */
1173 origObjectsAllocated = dvmHeapSourceGetValue(HS_OBJECTS_ALLOCATED, NULL, 0);
1174 origBytesAllocated = dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
1175
Carl Shapiro5a6071b2010-01-07 21:35:50 -08001176 dvmSweepMonitorList(&gDvm.monitorList, isUnmarkedObject);
1177
Carl Shapirof373efd2010-02-19 00:46:33 -08001178 numBitmaps = dvmHeapSourceGetNumHeaps();
Carl Shapirod77f7fd2010-04-05 19:23:31 -07001179 dvmHeapSourceGetObjectBitmaps(liveBits, markBits, numBitmaps);
Carl Shapirod25566d2010-03-11 20:39:47 -08001180 if (mode == GC_PARTIAL) {
1181 numSweepBitmaps = 1;
Carl Shapirod77f7fd2010-04-05 19:23:31 -07001182 assert((uintptr_t)gDvm.gcHeap->markContext.immuneLimit == liveBits[0].base);
Carl Shapirod25566d2010-03-11 20:39:47 -08001183 } else {
1184 numSweepBitmaps = numBitmaps;
1185 }
Barry Hayese168ebd2010-05-07 09:19:46 -07001186 for (i = 0; i < numSweepBitmaps; i++) {
1187 dvmHeapBitmapXorWalk(&markBits[i], &liveBits[i],
1188 sweepBitmapCallback, NULL);
1189 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001190
1191 *numFreed = origObjectsAllocated -
1192 dvmHeapSourceGetValue(HS_OBJECTS_ALLOCATED, NULL, 0);
1193 *sizeFreed = origBytesAllocated -
1194 dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
1195
1196#ifdef WITH_PROFILER
1197 if (gDvm.allocProf.enabled) {
1198 gDvm.allocProf.freeCount += *numFreed;
1199 gDvm.allocProf.freeSize += *sizeFreed;
1200 }
1201#endif
1202}