blob: 4bb917bc0b7216d4274aed2653b5506a4b0669c2 [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
28#define GC_DEBUG_PARANOID 2
29#define GC_DEBUG_BASIC 1
30#define GC_DEBUG_OFF 0
31#define GC_DEBUG(l) (GC_DEBUG_LEVEL >= (l))
32
33#if 1
34#define GC_DEBUG_LEVEL GC_DEBUG_PARANOID
35#else
36#define GC_DEBUG_LEVEL GC_DEBUG_OFF
37#endif
38
39#define VERBOSE_GC 0
40
41#define GC_LOG_TAG LOG_TAG "-gc"
42
43#if LOG_NDEBUG
44#define LOGV_GC(...) ((void)0)
45#define LOGD_GC(...) ((void)0)
46#else
47#define LOGV_GC(...) LOG(LOG_VERBOSE, GC_LOG_TAG, __VA_ARGS__)
48#define LOGD_GC(...) LOG(LOG_DEBUG, GC_LOG_TAG, __VA_ARGS__)
49#endif
50
51#if VERBOSE_GC
52#define LOGVV_GC(...) LOGV_GC(__VA_ARGS__)
53#else
54#define LOGVV_GC(...) ((void)0)
55#endif
56
57#define LOGI_GC(...) LOG(LOG_INFO, GC_LOG_TAG, __VA_ARGS__)
58#define LOGW_GC(...) LOG(LOG_WARN, GC_LOG_TAG, __VA_ARGS__)
59#define LOGE_GC(...) LOG(LOG_ERROR, GC_LOG_TAG, __VA_ARGS__)
60
61#define LOG_SCAN(...) LOGV_GC("SCAN: " __VA_ARGS__)
62#define LOG_MARK(...) LOGV_GC("MARK: " __VA_ARGS__)
63#define LOG_SWEEP(...) LOGV_GC("SWEEP: " __VA_ARGS__)
64#define LOG_REF(...) LOGV_GC("REF: " __VA_ARGS__)
65
66#define LOGV_SCAN(...) LOGVV_GC("SCAN: " __VA_ARGS__)
67#define LOGV_MARK(...) LOGVV_GC("MARK: " __VA_ARGS__)
68#define LOGV_SWEEP(...) LOGVV_GC("SWEEP: " __VA_ARGS__)
69#define LOGV_REF(...) LOGVV_GC("REF: " __VA_ARGS__)
70
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080071#ifndef PAGE_SIZE
72#define PAGE_SIZE 4096
73#endif
74#define ALIGN_UP_TO_PAGE_SIZE(p) \
75 (((size_t)(p) + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1))
76
77/* Do not cast the result of this to a boolean; the only set bit
78 * may be > 1<<8.
79 */
80static inline long isMarked(const DvmHeapChunk *hc, const GcMarkContext *ctx)
81 __attribute__((always_inline));
82static inline long isMarked(const DvmHeapChunk *hc, const GcMarkContext *ctx)
83{
84 return dvmHeapBitmapIsObjectBitSetInList(ctx->bitmaps, ctx->numBitmaps, hc);
85}
86
87static bool
88createMarkStack(GcMarkStack *stack)
89{
90 const Object **limit;
91 size_t size;
The Android Open Source Project99409882009-03-18 22:20:24 -070092 int fd, err;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080093
94 /* Create a stack big enough for the worst possible case,
95 * where the heap is perfectly full of the smallest object.
96 * TODO: be better about memory usage; use a smaller stack with
97 * overflow detection and recovery.
98 */
99 size = dvmHeapSourceGetIdealFootprint() * sizeof(Object*) /
100 (sizeof(Object) + HEAP_SOURCE_CHUNK_OVERHEAD);
101 size = ALIGN_UP_TO_PAGE_SIZE(size);
102 fd = ashmem_create_region("dalvik-heap-markstack", size);
103 if (fd < 0) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700104 LOGE_GC("Could not create %d-byte ashmem mark stack: %s\n",
105 size, strerror(errno));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800106 return false;
107 }
108 limit = (const Object **)mmap(NULL, size, PROT_READ | PROT_WRITE,
109 MAP_PRIVATE, fd, 0);
The Android Open Source Project99409882009-03-18 22:20:24 -0700110 err = errno;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800111 close(fd);
112 if (limit == MAP_FAILED) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700113 LOGE_GC("Could not mmap %d-byte ashmem mark stack: %s\n",
114 size, strerror(err));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800115 return false;
116 }
117
118 memset(stack, 0, sizeof(*stack));
119 stack->limit = limit;
120 stack->base = (const Object **)((uintptr_t)limit + size);
121 stack->top = stack->base;
122
123 return true;
124}
125
126static void
127destroyMarkStack(GcMarkStack *stack)
128{
129 munmap((char *)stack->limit,
130 (uintptr_t)stack->base - (uintptr_t)stack->limit);
131 memset(stack, 0, sizeof(*stack));
132}
133
134#define MARK_STACK_PUSH(stack, obj) \
135 do { \
136 *--(stack).top = (obj); \
137 } while (false)
138
139bool
140dvmHeapBeginMarkStep()
141{
142 GcMarkContext *mc = &gDvm.gcHeap->markContext;
143 HeapBitmap objectBitmaps[HEAP_SOURCE_MAX_HEAP_COUNT];
144 size_t numBitmaps;
145
146 if (!createMarkStack(&mc->stack)) {
147 return false;
148 }
149
150 numBitmaps = dvmHeapSourceGetObjectBitmaps(objectBitmaps,
151 HEAP_SOURCE_MAX_HEAP_COUNT);
152 if (numBitmaps <= 0) {
153 return false;
154 }
155
156 /* Create mark bitmaps that cover the same ranges as the
157 * current object bitmaps.
158 */
159 if (!dvmHeapBitmapInitListFromTemplates(mc->bitmaps, objectBitmaps,
160 numBitmaps, "mark"))
161 {
162 return false;
163 }
164
165 mc->numBitmaps = numBitmaps;
166 mc->finger = NULL;
167
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800168 return true;
169}
170
171static long setAndReturnMarkBit(GcMarkContext *ctx, const DvmHeapChunk *hc)
172 __attribute__((always_inline));
173static long
174setAndReturnMarkBit(GcMarkContext *ctx, const DvmHeapChunk *hc)
175{
176 return dvmHeapBitmapSetAndReturnObjectBitInList(ctx->bitmaps,
177 ctx->numBitmaps, hc);
178}
179
180static void _markObjectNonNullCommon(const Object *obj, GcMarkContext *ctx,
181 bool checkFinger, bool forceStack)
182 __attribute__((always_inline));
183static void
184_markObjectNonNullCommon(const Object *obj, GcMarkContext *ctx,
185 bool checkFinger, bool forceStack)
186{
187 DvmHeapChunk *hc;
188
189 assert(obj != NULL);
190
191#if GC_DEBUG(GC_DEBUG_PARANOID)
192//TODO: make sure we're locked
193 assert(obj != (Object *)gDvm.unlinkedJavaLangClass);
194 assert(dvmIsValidObject(obj));
195#endif
196
197 hc = ptr2chunk(obj);
198 if (!setAndReturnMarkBit(ctx, hc)) {
199 /* This object was not previously marked.
200 */
201 if (forceStack || (checkFinger && (void *)hc < ctx->finger)) {
202 /* This object will need to go on the mark stack.
203 */
204 MARK_STACK_PUSH(ctx->stack, obj);
205 }
206
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800207#if WITH_HPROF
208 if (gDvm.gcHeap->hprofContext != NULL) {
209 hprofMarkRootObject(gDvm.gcHeap->hprofContext, obj, 0);
210 }
211#endif
212#if DVM_TRACK_HEAP_MARKING
213 gDvm.gcHeap->markCount++;
214 gDvm.gcHeap->markSize += dvmHeapSourceChunkSize((void *)hc) +
215 HEAP_SOURCE_CHUNK_OVERHEAD;
216#endif
217
218 /* obj->clazz can be NULL if we catch an object between
219 * dvmMalloc() and DVM_OBJECT_INIT(). This is ok.
220 */
221 LOGV_MARK("0x%08x %s\n", (uint)obj,
222 obj->clazz == NULL ? "<null class>" : obj->clazz->name);
223 }
224}
225
226/* Used to mark objects when recursing. Recursion is done by moving
227 * the finger across the bitmaps in address order and marking child
228 * objects. Any newly-marked objects whose addresses are lower than
229 * the finger won't be visited by the bitmap scan, so those objects
230 * need to be added to the mark stack.
231 */
232static void
233markObjectNonNull(const Object *obj, GcMarkContext *ctx)
234{
235 _markObjectNonNullCommon(obj, ctx, true, false);
236}
237
238#define markObject(obj, ctx) \
239 do { \
240 Object *MO_obj_ = (Object *)(obj); \
241 if (MO_obj_ != NULL) { \
242 markObjectNonNull(MO_obj_, (ctx)); \
243 } \
244 } while (false)
245
246/* If the object hasn't already been marked, mark it and
247 * schedule it to be scanned for references.
248 *
249 * obj may not be NULL. The macro dvmMarkObject() should
250 * be used in situations where a reference may be NULL.
251 *
252 * This function may only be called when marking the root
253 * set. When recursing, use the internal markObject[NonNull]().
254 */
255void
256dvmMarkObjectNonNull(const Object *obj)
257{
258 _markObjectNonNullCommon(obj, &gDvm.gcHeap->markContext, false, false);
259}
260
261/* Mark the set of root objects.
262 *
263 * Things we need to scan:
264 * - System classes defined by root classloader
265 * - For each thread:
266 * - Interpreted stack, from top to "curFrame"
267 * - Dalvik registers (args + local vars)
268 * - JNI local references
269 * - Automatic VM local references (TrackedAlloc)
270 * - Associated Thread/VMThread object
271 * - ThreadGroups (could track & start with these instead of working
272 * upward from Threads)
273 * - Exception currently being thrown, if present
274 * - JNI global references
275 * - Interned string table
276 * - Primitive classes
277 * - Special objects
278 * - gDvm.outOfMemoryObj
279 * - Objects allocated with ALLOC_NO_GC
280 * - Objects pending finalization (but not yet finalized)
281 * - Objects in debugger object registry
282 *
283 * Don't need:
284 * - Native stack (for in-progress stuff in the VM)
285 * - The TrackedAlloc stuff watches all native VM references.
286 */
287void dvmHeapMarkRootSet()
288{
289 HeapRefTable *refs;
290 GcHeap *gcHeap;
291 Object **op;
292
293 gcHeap = gDvm.gcHeap;
294
295 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_STICKY_CLASS, 0);
296
297 LOG_SCAN("root class loader\n");
298 dvmGcScanRootClassLoader();
299 LOG_SCAN("primitive classes\n");
300 dvmGcScanPrimitiveClasses();
301
302 /* dvmGcScanRootThreadGroups() sets a bunch of
303 * different scan states internally.
304 */
305 HPROF_CLEAR_GC_SCAN_STATE();
306
307 LOG_SCAN("root thread groups\n");
308 dvmGcScanRootThreadGroups();
309
310 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_INTERNED_STRING, 0);
311
312 LOG_SCAN("interned strings\n");
313 dvmGcScanInternedStrings();
314
315 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_JNI_GLOBAL, 0);
316
317 LOG_SCAN("JNI global refs\n");
318 dvmGcMarkJniGlobalRefs();
319
320 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_REFERENCE_CLEANUP, 0);
321
322 LOG_SCAN("pending reference operations\n");
323 dvmHeapMarkLargeTableRefs(gcHeap->referenceOperations, true);
324
325 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_FINALIZING, 0);
326
327 LOG_SCAN("pending finalizations\n");
328 dvmHeapMarkLargeTableRefs(gcHeap->pendingFinalizationRefs, false);
329
330 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_DEBUGGER, 0);
331
332 LOG_SCAN("debugger refs\n");
333 dvmGcMarkDebuggerRefs();
334
335 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_VM_INTERNAL, 0);
336
337 /* Mark all ALLOC_NO_GC objects.
338 */
339 LOG_SCAN("ALLOC_NO_GC objects\n");
340 refs = &gcHeap->nonCollectableRefs;
341 op = refs->table;
342 while ((uintptr_t)op < (uintptr_t)refs->nextEntry) {
343 dvmMarkObjectNonNull(*(op++));
344 }
345
346 /* Mark any special objects we have sitting around.
347 */
348 LOG_SCAN("special objects\n");
349 dvmMarkObjectNonNull(gDvm.outOfMemoryObj);
350 dvmMarkObjectNonNull(gDvm.internalErrorObj);
Andy McFadden7fc3ce82009-07-14 15:57:23 -0700351 dvmMarkObjectNonNull(gDvm.noClassDefFoundErrorObj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800352//TODO: scan object references sitting in gDvm; use pointer begin & end
353
354 HPROF_CLEAR_GC_SCAN_STATE();
355}
356
357/*
358 * Nothing past this point is allowed to use dvmMarkObject*().
359 * Scanning/recursion must use markObject*(), which takes the
360 * finger into account.
361 */
362#define dvmMarkObjectNonNull __dont_use_dvmMarkObjectNonNull__
363
364
365/* Mark all of a ClassObject's interfaces.
366 */
367static void markInterfaces(const ClassObject *clazz, GcMarkContext *ctx)
368{
369 ClassObject **interfaces;
370 int interfaceCount;
371 int i;
372
373 /* Mark all interfaces.
374 */
375 interfaces = clazz->interfaces;
376 interfaceCount = clazz->interfaceCount;
377 for (i = 0; i < interfaceCount; i++) {
378 markObjectNonNull((Object *)*interfaces, ctx);
379 interfaces++;
380 }
381}
382
383/* Mark all objects referred to by a ClassObject's static fields.
384 */
385static void scanStaticFields(const ClassObject *clazz, GcMarkContext *ctx)
386{
387 StaticField *f;
388 int i;
389
390 //TODO: Optimize this with a bit vector or something
391 f = clazz->sfields;
392 for (i = 0; i < clazz->sfieldCount; i++) {
393 char c = f->field.signature[0];
394 if (c == '[' || c == 'L') {
395 /* It's an array or class reference.
396 */
397 markObject((Object *)f->value.l, ctx);
398 }
399 f++;
400 }
401}
402
403/* Mark all objects referred to by a DataObject's instance fields.
404 */
405static void scanInstanceFields(const DataObject *obj, ClassObject *clazz,
406 GcMarkContext *ctx)
407{
Jean-Baptiste Querube323ec2009-08-10 13:41:39 -0700408 if (false && clazz->refOffsets != CLASS_WALK_SUPER) {
Barry Hayeseac47ed2009-06-22 11:45:20 -0700409 unsigned int refOffsets = clazz->refOffsets;
410 while (refOffsets != 0) {
411 const int rshift = CLZ(refOffsets);
412 refOffsets &= ~(CLASS_HIGH_BIT >> rshift);
413 markObject(dvmGetFieldObject((Object*)obj,
414 CLASS_OFFSET_FROM_CLZ(rshift)), ctx);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800415 }
Barry Hayeseac47ed2009-06-22 11:45:20 -0700416 } else {
417 while (clazz != NULL) {
418 InstField *f;
419 int i;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800420
Barry Hayeseac47ed2009-06-22 11:45:20 -0700421 /* All of the fields that contain object references
422 * are guaranteed to be at the beginning of the ifields list.
423 */
424 f = clazz->ifields;
425 for (i = 0; i < clazz->ifieldRefCount; i++) {
426 /* Mark the array or object reference.
427 * May be NULL.
428 *
429 * Note that, per the comment on struct InstField,
430 * f->byteOffset is the offset from the beginning of
431 * obj, not the offset into obj->instanceData.
432 */
433 markObject(dvmGetFieldObject((Object*)obj, f->byteOffset), ctx);
434 f++;
435 }
436
437 /* This will be NULL when we hit java.lang.Object
438 */
439 clazz = clazz->super;
440 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800441 }
442}
443
444/* Mark all objects referred to by the array's contents.
445 */
446static void scanObjectArray(const ArrayObject *array, GcMarkContext *ctx)
447{
448 Object **contents;
449 u4 length;
450 u4 i;
451
452 contents = (Object **)array->contents;
453 length = array->length;
454
455 for (i = 0; i < length; i++) {
456 markObject(*contents, ctx); // may be NULL
457 contents++;
458 }
459}
460
461/* Mark all objects referred to by the ClassObject.
462 */
463static void scanClassObject(const ClassObject *clazz, GcMarkContext *ctx)
464{
465 LOGV_SCAN("---------> %s\n", clazz->name);
466
467 if (IS_CLASS_FLAG_SET(clazz, CLASS_ISARRAY)) {
468 /* We're an array; mark the class object of the contents
469 * of the array.
470 *
471 * Note that we won't necessarily reach the array's element
472 * class by scanning the array contents; the array may be
473 * zero-length, or may only contain null objects.
474 */
475 markObjectNonNull((Object *)clazz->elementClass, ctx);
476 }
477
478 /* We scan these explicitly in case the only remaining
479 * reference to a particular class object is via a data
480 * object; we may not be guaranteed to reach all
481 * live class objects via a classloader.
482 */
483 markObject((Object *)clazz->super, ctx); // may be NULL (java.lang.Object)
484 markObject(clazz->classLoader, ctx); // may be NULL
485
486 scanStaticFields(clazz, ctx);
487 markInterfaces(clazz, ctx);
488}
489
490/* Mark all objects that obj refers to.
491 *
492 * Called on every object in markList.
493 */
494static void scanObject(const Object *obj, GcMarkContext *ctx)
495{
496 ClassObject *clazz;
497
498 assert(dvmIsValidObject(obj));
499 LOGV_SCAN("0x%08x %s\n", (uint)obj, obj->clazz->name);
500
501#if WITH_HPROF
502 if (gDvm.gcHeap->hprofContext != NULL) {
503 hprofDumpHeapObject(gDvm.gcHeap->hprofContext, obj);
504 }
505#endif
506
507 /* Get and mark the class object for this particular instance.
508 */
509 clazz = obj->clazz;
510 if (clazz == NULL) {
511 /* This can happen if we catch an object between
512 * dvmMalloc() and DVM_OBJECT_INIT(). The object
513 * won't contain any references yet, so we can
514 * just skip it.
515 */
516 return;
517 } else if (clazz == gDvm.unlinkedJavaLangClass) {
518 /* This class hasn't been linked yet. We're guaranteed
519 * that the object doesn't contain any references that
520 * aren't already tracked, so we can skip scanning it.
521 *
522 * NOTE: unlinkedJavaLangClass is not on the heap, so
523 * it's very important that we don't try marking it.
524 */
525 return;
526 }
Barry Hayes3592d622009-03-16 16:10:35 -0700527
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800528 assert(dvmIsValidObject((Object *)clazz));
529 markObjectNonNull((Object *)clazz, ctx);
530
531 /* Mark any references in this object.
532 */
533 if (IS_CLASS_FLAG_SET(clazz, CLASS_ISARRAY)) {
534 /* It's an array object.
535 */
536 if (IS_CLASS_FLAG_SET(clazz, CLASS_ISOBJECTARRAY)) {
537 /* It's an array of object references.
538 */
539 scanObjectArray((ArrayObject *)obj, ctx);
540 }
541 // else there's nothing else to scan
542 } else {
543 /* It's a DataObject-compatible object.
544 */
545 scanInstanceFields((DataObject *)obj, clazz, ctx);
546
547 if (IS_CLASS_FLAG_SET(clazz, CLASS_ISREFERENCE)) {
548 GcHeap *gcHeap = gDvm.gcHeap;
549 Object *referent;
550
551 /* It's a subclass of java/lang/ref/Reference.
552 * The fields in this class have been arranged
553 * such that scanInstanceFields() did not actually
554 * mark the "referent" field; we need to handle
555 * it specially.
556 *
557 * If the referent already has a strong mark (isMarked(referent)),
558 * we don't care about its reference status.
559 */
560 referent = dvmGetFieldObject(obj,
561 gDvm.offJavaLangRefReference_referent);
562 if (referent != NULL &&
563 !isMarked(ptr2chunk(referent), &gcHeap->markContext))
564 {
565 u4 refFlags;
566
567 if (gcHeap->markAllReferents) {
568 LOG_REF("Hard-marking a reference\n");
569
570 /* Don't bother with normal reference-following
571 * behavior, just mark the referent. This should
572 * only be used when following objects that just
573 * became scheduled for finalization.
574 */
575 markObjectNonNull(referent, ctx);
576 goto skip_reference;
577 }
578
579 /* See if this reference was handled by a previous GC.
580 */
581 if (dvmGetFieldObject(obj,
582 gDvm.offJavaLangRefReference_vmData) ==
583 SCHEDULED_REFERENCE_MAGIC)
584 {
585 LOG_REF("Skipping scheduled reference\n");
586
587 /* Don't reschedule it, but make sure that its
588 * referent doesn't get collected (in case it's
589 * a PhantomReference and wasn't cleared automatically).
590 */
591 //TODO: Mark these after handling all new refs of
592 // this strength, in case the new refs refer
593 // to the same referent. Not a very common
594 // case, though.
595 markObjectNonNull(referent, ctx);
596 goto skip_reference;
597 }
598
599 /* Find out what kind of reference is pointing
600 * to referent.
601 */
602 refFlags = GET_CLASS_FLAG_GROUP(clazz,
603 CLASS_ISREFERENCE |
604 CLASS_ISWEAKREFERENCE |
605 CLASS_ISPHANTOMREFERENCE);
606
607 /* We use the vmData field of Reference objects
608 * as a next pointer in a singly-linked list.
609 * That way, we don't need to allocate any memory
610 * while we're doing a GC.
611 */
612#define ADD_REF_TO_LIST(list, ref) \
613 do { \
614 Object *ARTL_ref_ = (/*de-const*/Object *)(ref); \
615 dvmSetFieldObject(ARTL_ref_, \
616 gDvm.offJavaLangRefReference_vmData, list); \
617 list = ARTL_ref_; \
618 } while (false)
619
620 /* At this stage, we just keep track of all of
621 * the live references that we've seen. Later,
622 * we'll walk through each of these lists and
623 * deal with the referents.
624 */
625 if (refFlags == CLASS_ISREFERENCE) {
626 /* It's a soft reference. Depending on the state,
627 * we'll attempt to collect all of them, some of
628 * them, or none of them.
629 */
630 if (gcHeap->softReferenceCollectionState ==
631 SR_COLLECT_NONE)
632 {
633 sr_collect_none:
634 markObjectNonNull(referent, ctx);
635 } else if (gcHeap->softReferenceCollectionState ==
636 SR_COLLECT_ALL)
637 {
638 sr_collect_all:
639 ADD_REF_TO_LIST(gcHeap->softReferences, obj);
640 } else {
641 /* We'll only try to collect half of the
642 * referents.
643 */
644 if (gcHeap->softReferenceColor++ & 1) {
645 goto sr_collect_none;
646 }
647 goto sr_collect_all;
648 }
649 } else {
650 /* It's a weak or phantom reference.
651 * Clearing CLASS_ISREFERENCE will reveal which.
652 */
653 refFlags &= ~CLASS_ISREFERENCE;
654 if (refFlags == CLASS_ISWEAKREFERENCE) {
655 ADD_REF_TO_LIST(gcHeap->weakReferences, obj);
656 } else if (refFlags == CLASS_ISPHANTOMREFERENCE) {
657 ADD_REF_TO_LIST(gcHeap->phantomReferences, obj);
658 } else {
659 assert(!"Unknown reference type");
660 }
661 }
662#undef ADD_REF_TO_LIST
663 }
664 }
665
666 skip_reference:
667 /* If this is a class object, mark various other things that
668 * its internals point to.
669 *
670 * All class objects are instances of java.lang.Class,
671 * including the java.lang.Class class object.
672 */
673 if (clazz == gDvm.classJavaLangClass) {
674 scanClassObject((ClassObject *)obj, ctx);
675 }
676 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800677}
678
679static void
680processMarkStack(GcMarkContext *ctx)
681{
682 const Object **const base = ctx->stack.base;
683
684 /* Scan anything that's on the mark stack.
685 * We can't use the bitmaps anymore, so use
686 * a finger that points past the end of them.
687 */
688 ctx->finger = (void *)ULONG_MAX;
689 while (ctx->stack.top != base) {
690 scanObject(*ctx->stack.top++, ctx);
691 }
692}
693
694#ifndef NDEBUG
695static uintptr_t gLastFinger = 0;
696#endif
697
698static bool
699scanBitmapCallback(size_t numPtrs, void **ptrs, const void *finger, void *arg)
700{
701 GcMarkContext *ctx = (GcMarkContext *)arg;
702 size_t i;
703
704#ifndef NDEBUG
705 assert((uintptr_t)finger >= gLastFinger);
706 gLastFinger = (uintptr_t)finger;
707#endif
708
709 ctx->finger = finger;
710 for (i = 0; i < numPtrs; i++) {
711 /* The pointers we're getting back are DvmHeapChunks,
712 * not Objects.
713 */
714 scanObject(chunk2ptr(*ptrs++), ctx);
715 }
716
717 return true;
718}
719
720/* Given bitmaps with the root set marked, find and mark all
721 * reachable objects. When this returns, the entire set of
722 * live objects will be marked and the mark stack will be empty.
723 */
724void dvmHeapScanMarkedObjects()
725{
726 GcMarkContext *ctx = &gDvm.gcHeap->markContext;
727
728 assert(ctx->finger == NULL);
729
730 /* The bitmaps currently have bits set for the root set.
731 * Walk across the bitmaps and scan each object.
732 */
733#ifndef NDEBUG
734 gLastFinger = 0;
735#endif
736 dvmHeapBitmapWalkList(ctx->bitmaps, ctx->numBitmaps,
737 scanBitmapCallback, ctx);
738
739 /* We've walked the mark bitmaps. Scan anything that's
740 * left on the mark stack.
741 */
742 processMarkStack(ctx);
743
744 LOG_SCAN("done with marked objects\n");
745}
746
747/** @return true if we need to schedule a call to clear().
748 */
749static bool clearReference(Object *reference)
750{
751 /* This is what the default implementation of Reference.clear()
752 * does. We're required to clear all references to a given
753 * referent atomically, so we can't pop in and out of interp
754 * code each time.
755 *
756 * Also, someone may have subclassed one of the basic Reference
757 * types, overriding clear(). We can't trust the clear()
758 * implementation to call super.clear(); we cannot let clear()
759 * resurrect the referent. If we clear it here, we can safely
760 * call any overriding implementations.
761 */
762 dvmSetFieldObject(reference,
763 gDvm.offJavaLangRefReference_referent, NULL);
764
765#if FANCY_REFERENCE_SUBCLASS
766 /* See if clear() has actually been overridden. If so,
767 * we need to schedule a call to it before calling enqueue().
768 */
769 if (reference->clazz->vtable[gDvm.voffJavaLangRefReference_clear]->clazz !=
770 gDvm.classJavaLangRefReference)
771 {
772 /* clear() has been overridden; return true to indicate
773 * that we need to schedule a call to the real clear()
774 * implementation.
775 */
776 return true;
777 }
778#endif
779
780 return false;
781}
782
783/** @return true if we need to schedule a call to enqueue().
784 */
785static bool enqueueReference(Object *reference)
786{
787#if FANCY_REFERENCE_SUBCLASS
788 /* See if this reference class has overridden enqueue();
789 * if not, we can take a shortcut.
790 */
791 if (reference->clazz->vtable[gDvm.voffJavaLangRefReference_enqueue]->clazz
792 == gDvm.classJavaLangRefReference)
793#endif
794 {
795 Object *queue = dvmGetFieldObject(reference,
796 gDvm.offJavaLangRefReference_queue);
797 Object *queueNext = dvmGetFieldObject(reference,
798 gDvm.offJavaLangRefReference_queueNext);
799 if (queue == NULL || queueNext != NULL) {
800 /* There is no queue, or the reference has already
801 * been enqueued. The Reference.enqueue() method
802 * will do nothing even if we call it.
803 */
804 return false;
805 }
806 }
807
808 /* We need to call enqueue(), but if we called it from
809 * here we'd probably deadlock. Schedule a call.
810 */
811 return true;
812}
813
814/* All objects for stronger reference levels have been
815 * marked before this is called.
816 */
817void dvmHeapHandleReferences(Object *refListHead, enum RefType refType)
818{
819 Object *reference;
820 GcMarkContext *markContext = &gDvm.gcHeap->markContext;
821 const int offVmData = gDvm.offJavaLangRefReference_vmData;
822 const int offReferent = gDvm.offJavaLangRefReference_referent;
823 bool workRequired = false;
824
825size_t numCleared = 0;
826size_t numEnqueued = 0;
827 reference = refListHead;
828 while (reference != NULL) {
829 Object *next;
830 Object *referent;
831
832 /* Pull the interesting fields out of the Reference object.
833 */
834 next = dvmGetFieldObject(reference, offVmData);
835 referent = dvmGetFieldObject(reference, offReferent);
836
837 //TODO: when handling REF_PHANTOM, unlink any references
838 // that fail this initial if(). We need to re-walk
839 // the list, and it would be nice to avoid the extra
840 // work.
841 if (referent != NULL && !isMarked(ptr2chunk(referent), markContext)) {
842 bool schedClear, schedEnqueue;
843
844 /* This is the strongest reference that refers to referent.
845 * Do the right thing.
846 */
847 switch (refType) {
848 case REF_SOFT:
849 case REF_WEAK:
850 schedClear = clearReference(reference);
851 schedEnqueue = enqueueReference(reference);
852 break;
853 case REF_PHANTOM:
854 /* PhantomReferences are not cleared automatically.
855 * Until someone clears it (or the reference itself
856 * is collected), the referent must remain alive.
857 *
858 * It's necessary to fully mark the referent because
859 * it will still be present during the next GC, and
860 * all objects that it points to must be valid.
861 * (The referent will be marked outside of this loop,
862 * after handing all references of this strength, in
863 * case multiple references point to the same object.)
864 */
865 schedClear = false;
866
867 /* A PhantomReference is only useful with a
868 * queue, but since it's possible to create one
869 * without a queue, we need to check.
870 */
871 schedEnqueue = enqueueReference(reference);
872 break;
873 default:
874 assert(!"Bad reference type");
875 schedClear = false;
876 schedEnqueue = false;
877 break;
878 }
879numCleared += schedClear ? 1 : 0;
880numEnqueued += schedEnqueue ? 1 : 0;
881
882 if (schedClear || schedEnqueue) {
883 uintptr_t workBits;
884
885 /* Stuff the clear/enqueue bits in the bottom of
886 * the pointer. Assumes that objects are 8-byte
887 * aligned.
888 *
889 * Note that we are adding the *Reference* (which
890 * is by definition already marked at this point) to
891 * this list; we're not adding the referent (which
892 * has already been cleared).
893 */
894 assert(((intptr_t)reference & 3) == 0);
895 assert(((WORKER_CLEAR | WORKER_ENQUEUE) & ~3) == 0);
896 workBits = (schedClear ? WORKER_CLEAR : 0) |
897 (schedEnqueue ? WORKER_ENQUEUE : 0);
898 if (!dvmHeapAddRefToLargeTable(
899 &gDvm.gcHeap->referenceOperations,
900 (Object *)((uintptr_t)reference | workBits)))
901 {
902 LOGE_HEAP("dvmMalloc(): no room for any more "
903 "reference operations\n");
904 dvmAbort();
905 }
906 workRequired = true;
907 }
908
909 if (refType != REF_PHANTOM) {
910 /* Let later GCs know not to reschedule this reference.
911 */
912 dvmSetFieldObject(reference, offVmData,
913 SCHEDULED_REFERENCE_MAGIC);
914 } // else this is handled later for REF_PHANTOM
915
916 } // else there was a stronger reference to the referent.
917
918 reference = next;
919 }
920#define refType2str(r) \
921 ((r) == REF_SOFT ? "soft" : ( \
922 (r) == REF_WEAK ? "weak" : ( \
923 (r) == REF_PHANTOM ? "phantom" : "UNKNOWN" )))
924LOGD_HEAP("dvmHeapHandleReferences(): cleared %zd, enqueued %zd %s references\n", numCleared, numEnqueued, refType2str(refType));
925
926 /* Walk though the reference list again, and mark any non-clear/marked
927 * referents. Only PhantomReferences can have non-clear referents
928 * at this point.
929 */
930 if (refType == REF_PHANTOM) {
931 bool scanRequired = false;
932
933 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_REFERENCE_CLEANUP, 0);
934 reference = refListHead;
935 while (reference != NULL) {
936 Object *next;
937 Object *referent;
938
939 /* Pull the interesting fields out of the Reference object.
940 */
941 next = dvmGetFieldObject(reference, offVmData);
942 referent = dvmGetFieldObject(reference, offReferent);
943
944 if (referent != NULL && !isMarked(ptr2chunk(referent), markContext)) {
945 markObjectNonNull(referent, markContext);
946 scanRequired = true;
947
948 /* Let later GCs know not to reschedule this reference.
949 */
950 dvmSetFieldObject(reference, offVmData,
951 SCHEDULED_REFERENCE_MAGIC);
952 }
953
954 reference = next;
955 }
956 HPROF_CLEAR_GC_SCAN_STATE();
957
958 if (scanRequired) {
959 processMarkStack(markContext);
960 }
961 }
962
963 if (workRequired) {
964 dvmSignalHeapWorker(false);
965 }
966}
967
968
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 */
989 if (!dvmHeapInitHeapRefTable(&newPendingRefs, 128)) {
990 //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) {
1010 DvmHeapChunk *hc;
1011
1012 hc = ptr2chunk(*ref);
1013 if (!isMarked(hc, markContext)) {
1014 if (!dvmHeapAddToHeapRefTable(&newPendingRefs, *ref)) {
1015 //TODO: add the current table and allocate
1016 // a new, smaller one.
1017 LOGE_GC("dvmHeapScheduleFinalizations(): "
1018 "no room for any more pending finalizations: %zd\n",
1019 dvmHeapNumHeapRefTableEntries(&newPendingRefs));
1020 dvmAbort();
1021 }
1022 newPendCount++;
1023 } else {
1024 /* This ref is marked, so will remain on finalizableRefs.
1025 */
1026 if (newPendCount > 0) {
1027 /* Copy it up to fill the holes.
1028 */
1029 *gapRef++ = *ref;
1030 } else {
1031 /* No holes yet; don't bother copying.
1032 */
1033 gapRef++;
1034 }
1035 }
1036 ref++;
1037 }
1038 finRefs->refs.nextEntry = gapRef;
1039 //TODO: if the table is empty when we're done, free it.
1040 totalPendCount += newPendCount;
1041 finRefs = finRefs->next;
1042 }
1043 LOGD_GC("dvmHeapScheduleFinalizations(): %zd finalizers triggered.\n",
1044 totalPendCount);
1045 if (totalPendCount == 0) {
1046 /* No objects required finalization.
1047 * Free the empty temporary table.
1048 */
1049 dvmClearReferenceTable(&newPendingRefs);
1050 return;
1051 }
1052
1053 /* Add the new pending refs to the main list.
1054 */
1055 if (!dvmHeapAddTableToLargeTable(&gDvm.gcHeap->pendingFinalizationRefs,
1056 &newPendingRefs))
1057 {
1058 LOGE_GC("dvmHeapScheduleFinalizations(): can't insert new "
1059 "pending finalizations\n");
1060 dvmAbort();
1061 }
1062
1063 //TODO: try compacting the main list with a memcpy loop
1064
1065 /* Mark the refs we just moved; we don't want them or their
1066 * children to get swept yet.
1067 */
1068 ref = newPendingRefs.table;
1069 lastRef = newPendingRefs.nextEntry;
1070 assert(ref < lastRef);
1071 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_FINALIZING, 0);
1072 while (ref < lastRef) {
1073 markObjectNonNull(*ref, markContext);
1074 ref++;
1075 }
1076 HPROF_CLEAR_GC_SCAN_STATE();
1077
1078 /* Set markAllReferents so that we don't collect referents whose
1079 * only references are in final-reachable objects.
1080 * TODO: eventually provide normal reference behavior by properly
1081 * marking these references.
1082 */
1083 gDvm.gcHeap->markAllReferents = true;
1084 processMarkStack(markContext);
1085 gDvm.gcHeap->markAllReferents = false;
1086
1087 dvmSignalHeapWorker(false);
1088}
1089
1090void dvmHeapFinishMarkStep()
1091{
1092 HeapBitmap *markBitmap;
1093 HeapBitmap objectBitmap;
1094 GcMarkContext *markContext;
1095
1096 markContext = &gDvm.gcHeap->markContext;
1097
1098 /* The sweep step freed every object that appeared in the
1099 * HeapSource bitmaps that didn't appear in the mark bitmaps.
1100 * The new state of the HeapSource is exactly the final
1101 * mark bitmaps, so swap them in.
1102 *
1103 * The old bitmaps will be swapped into the context so that
1104 * we can clean them up.
1105 */
1106 dvmHeapSourceReplaceObjectBitmaps(markContext->bitmaps,
1107 markContext->numBitmaps);
1108
1109 /* Clean up the old HeapSource bitmaps and anything else associated
1110 * with the marking process.
1111 */
1112 dvmHeapBitmapDeleteList(markContext->bitmaps, markContext->numBitmaps);
1113 destroyMarkStack(&markContext->stack);
1114
1115 memset(markContext, 0, sizeof(*markContext));
1116}
1117
1118#if WITH_HPROF && WITH_HPROF_UNREACHABLE
1119static bool
1120hprofUnreachableBitmapCallback(size_t numPtrs, void **ptrs,
1121 const void *finger, void *arg)
1122{
1123 hprof_context_t *hctx = (hprof_context_t *)arg;
1124 size_t i;
1125
1126 for (i = 0; i < numPtrs; i++) {
1127 Object *obj;
1128
1129 /* The pointers we're getting back are DvmHeapChunks, not
1130 * Objects.
1131 */
1132 obj = (Object *)chunk2ptr(*ptrs++);
1133
1134 hprofMarkRootObject(hctx, obj, 0);
1135 hprofDumpHeapObject(hctx, obj);
1136 }
1137
1138 return true;
1139}
1140
1141static void
1142hprofDumpUnmarkedObjects(const HeapBitmap markBitmaps[],
1143 const HeapBitmap objectBitmaps[], size_t numBitmaps)
1144{
1145 hprof_context_t *hctx = gDvm.gcHeap->hprofContext;
1146 if (hctx == NULL) {
1147 return;
1148 }
1149
1150 LOGI("hprof: dumping unreachable objects\n");
1151
1152 HPROF_SET_GC_SCAN_STATE(HPROF_UNREACHABLE, 0);
1153
1154 dvmHeapBitmapXorWalkLists(markBitmaps, objectBitmaps, numBitmaps,
1155 hprofUnreachableBitmapCallback, hctx);
1156
1157 HPROF_CLEAR_GC_SCAN_STATE();
1158}
1159#endif
1160
1161static bool
1162sweepBitmapCallback(size_t numPtrs, void **ptrs, const void *finger, void *arg)
1163{
1164 const ClassObject *const classJavaLangClass = gDvm.classJavaLangClass;
1165 size_t i;
Barry Hayesdde8ab02009-05-20 12:10:36 -07001166 void **origPtrs = ptrs;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001167
1168 for (i = 0; i < numPtrs; i++) {
1169 DvmHeapChunk *hc;
1170 Object *obj;
1171
1172 /* The pointers we're getting back are DvmHeapChunks, not
1173 * Objects.
1174 */
1175 hc = (DvmHeapChunk *)*ptrs++;
1176 obj = (Object *)chunk2ptr(hc);
1177
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001178 /* Free the monitor associated with the object.
1179 */
1180 dvmFreeObjectMonitor(obj);
1181
1182 /* NOTE: Dereferencing clazz is dangerous. If obj was the last
1183 * one to reference its class object, the class object could be
1184 * on the sweep list, and could already have been swept, leaving
1185 * us with a stale pointer.
1186 */
1187 LOGV_SWEEP("FREE: 0x%08x %s\n", (uint)obj, obj->clazz->name);
1188
1189 /* This assumes that java.lang.Class will never go away.
1190 * If it can, and we were the last reference to it, it
1191 * could have already been swept. However, even in that case,
1192 * gDvm.classJavaLangClass should still have a useful
1193 * value.
1194 */
1195 if (obj->clazz == classJavaLangClass) {
1196 LOGV_SWEEP("---------------> %s\n", ((ClassObject *)obj)->name);
1197 /* dvmFreeClassInnards() may have already been called,
1198 * but it's safe to call on the same ClassObject twice.
1199 */
1200 dvmFreeClassInnards((ClassObject *)obj);
1201 }
1202
1203#if 0
1204 /* Overwrite the to-be-freed object to make stale references
1205 * more obvious.
1206 */
1207 {
1208 int chunklen;
1209 ClassObject *clazz = obj->clazz;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001210 chunklen = dvmHeapSourceChunkSize(hc);
1211 memset(hc, 0xa5, chunklen);
1212 obj->clazz = (ClassObject *)((uintptr_t)clazz ^ 0xffffffff);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001213 }
1214#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001215 }
Barry Hayesdde8ab02009-05-20 12:10:36 -07001216 // TODO: dvmHeapSourceFreeList has a loop, just like the above
1217 // does. Consider collapsing the two loops to save overhead.
1218 dvmHeapSourceFreeList(numPtrs, origPtrs);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001219
1220 return true;
1221}
1222
1223/* A function suitable for passing to dvmHashForeachRemove()
1224 * to clear out any unmarked objects. Clears the low bits
1225 * of the pointer because the intern table may set them.
1226 */
1227static int isUnmarkedObject(void *object)
1228{
1229 return !isMarked(ptr2chunk((uintptr_t)object & ~(HB_OBJECT_ALIGNMENT-1)),
1230 &gDvm.gcHeap->markContext);
1231}
1232
1233/* Walk through the list of objects that haven't been
1234 * marked and free them.
1235 */
1236void
1237dvmHeapSweepUnmarkedObjects(int *numFreed, size_t *sizeFreed)
1238{
1239 const HeapBitmap *markBitmaps;
1240 const GcMarkContext *markContext;
1241 HeapBitmap objectBitmaps[HEAP_SOURCE_MAX_HEAP_COUNT];
1242 size_t origObjectsAllocated;
1243 size_t origBytesAllocated;
1244 size_t numBitmaps;
1245
1246 /* All reachable objects have been marked.
1247 * Detach any unreachable interned strings before
1248 * we sweep.
1249 */
1250 dvmGcDetachDeadInternedStrings(isUnmarkedObject);
1251
1252 /* Free any known objects that are not marked.
1253 */
1254 origObjectsAllocated = dvmHeapSourceGetValue(HS_OBJECTS_ALLOCATED, NULL, 0);
1255 origBytesAllocated = dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
1256
1257 markContext = &gDvm.gcHeap->markContext;
1258 markBitmaps = markContext->bitmaps;
1259 numBitmaps = dvmHeapSourceGetObjectBitmaps(objectBitmaps,
1260 HEAP_SOURCE_MAX_HEAP_COUNT);
1261#ifndef NDEBUG
1262 if (numBitmaps != markContext->numBitmaps) {
1263 LOGE("heap bitmap count mismatch: %zd != %zd\n",
1264 numBitmaps, markContext->numBitmaps);
1265 dvmAbort();
1266 }
1267#endif
1268
1269#if WITH_HPROF && WITH_HPROF_UNREACHABLE
1270 hprofDumpUnmarkedObjects(markBitmaps, objectBitmaps, numBitmaps);
1271#endif
1272
1273 dvmHeapBitmapXorWalkLists(markBitmaps, objectBitmaps, numBitmaps,
1274 sweepBitmapCallback, NULL);
1275
1276 *numFreed = origObjectsAllocated -
1277 dvmHeapSourceGetValue(HS_OBJECTS_ALLOCATED, NULL, 0);
1278 *sizeFreed = origBytesAllocated -
1279 dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
1280
1281#ifdef WITH_PROFILER
1282 if (gDvm.allocProf.enabled) {
1283 gDvm.allocProf.freeCount += *numFreed;
1284 gDvm.allocProf.freeSize += *sizeFreed;
1285 }
1286#endif
1287}