blob: 865e154ca660e24f5c3d9ee109be1619d1ea329b [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");
245 dvmHeapMarkLargeTableRefs(gcHeap->referenceOperations, true);
246
247 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_FINALIZING, 0);
248
249 LOG_SCAN("pending finalizations\n");
250 dvmHeapMarkLargeTableRefs(gcHeap->pendingFinalizationRefs, false);
251
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 Shapiro29540742010-03-26 15:34:39 -0700600 LargeHeapRefTable **table;
601 Object *op;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800602
Carl Shapiro29540742010-03-26 15:34:39 -0700603 assert(((uintptr_t)ref & 3) == 0);
604 assert((WORKER_ENQUEUE & ~3) == 0);
605 assert(dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queue) != NULL);
606 assert(dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queueNext) == NULL);
607 /* Stuff the enqueue bit in the bottom of the pointer.
608 * Assumes that objects are 8-byte aligned.
Andy McFaddenb18992f2009-09-25 10:42:15 -0700609 *
Carl Shapiro29540742010-03-26 15:34:39 -0700610 * Note that we are adding the *Reference* (which
611 * is by definition already marked at this point) to
612 * this list; we're not adding the referent (which
613 * has already been cleared).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800614 */
Carl Shapiro29540742010-03-26 15:34:39 -0700615 table = &gDvm.gcHeap->referenceOperations;
616 op = (Object *)((uintptr_t)ref | WORKER_ENQUEUE);
617 if (!dvmHeapAddRefToLargeTable(table, op)) {
618 LOGE_HEAP("enqueueReference(): no room for any more "
619 "reference operations\n");
620 dvmAbort();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800621 }
622}
623
Carl Shapiro29540742010-03-26 15:34:39 -0700624/*
625 * Walks the reference list marking any references subject to the
626 * reference clearing policy. References with a black referent are
627 * removed from the list. References with white referents biased
628 * toward saving are blackened and also removed from the list.
629 */
630void dvmHandleSoftRefs(Object **list)
631{
632 GcMarkContext *markContext;
633 Object *ref, *referent;
634 Object *prev, *next;
635 size_t referentOffset, vmDataOffset;
636 unsigned counter;
637 bool marked;
638
639 markContext = &gDvm.gcHeap->markContext;
640 vmDataOffset = gDvm.offJavaLangRefReference_vmData;
641 referentOffset = gDvm.offJavaLangRefReference_referent;
642 counter = 0;
643 prev = next = NULL;
644 ref = *list;
645 while (ref != NULL) {
646 referent = dvmGetFieldObject(ref, referentOffset);
647 next = dvmGetFieldObject(ref, vmDataOffset);
648 assert(referent != NULL);
649 marked = isMarked(referent, markContext);
650 if (!marked && ((++counter) & 1)) {
651 /* Referent is white and biased toward saving, mark it. */
Barry Hayese1bccb92010-05-18 09:48:37 -0700652 assert(referent != NULL);
653 markObject(referent, markContext);
Carl Shapiro29540742010-03-26 15:34:39 -0700654 marked = true;
655 }
656 if (marked) {
657 /* Referent is black, unlink it. */
658 if (prev != NULL) {
659 dvmSetFieldObject(ref, vmDataOffset, NULL);
660 dvmSetFieldObject(prev, vmDataOffset, next);
661 }
662 } else {
663 /* Referent is white, skip over it. */
664 prev = ref;
665 }
666 ref = next;
667 }
668 /*
669 * Restart the mark with the newly black references added to the
670 * root set.
671 */
672 processMarkStack(markContext);
673}
674
675/*
676 * Walks the reference list and clears references with an unmarked
677 * (white) referents. Cleared references registered to a reference
678 * queue are scheduled for appending by the heap worker thread.
679 */
680void dvmClearWhiteRefs(Object **list)
681{
682 GcMarkContext *markContext;
683 Object *ref, *referent;
684 size_t referentOffset, vmDataOffset;
685 bool doSignal;
686
687 markContext = &gDvm.gcHeap->markContext;
688 vmDataOffset = gDvm.offJavaLangRefReference_vmData;
689 referentOffset = gDvm.offJavaLangRefReference_referent;
690 doSignal = false;
691 while (*list != NULL) {
692 ref = *list;
693 referent = dvmGetFieldObject(ref, referentOffset);
694 *list = dvmGetFieldObject(ref, vmDataOffset);
695 assert(referent != NULL);
696 if (!isMarked(referent, markContext)) {
697 /* Referent is "white", clear it. */
698 clearReference(ref);
699 if (isEnqueuable(ref)) {
700 enqueueReference(ref);
701 doSignal = true;
702 }
703 }
704 }
705 /*
706 * If we cleared a reference with a reference queue we must notify
707 * the heap worker to append the reference.
708 */
709 if (doSignal) {
710 dvmSignalHeapWorker(false);
711 }
712 assert(*list == NULL);
713}
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800714
715/* Find unreachable objects that need to be finalized,
716 * and schedule them for finalization.
717 */
718void dvmHeapScheduleFinalizations()
719{
720 HeapRefTable newPendingRefs;
721 LargeHeapRefTable *finRefs = gDvm.gcHeap->finalizableRefs;
722 Object **ref;
723 Object **lastRef;
724 size_t totalPendCount;
725 GcMarkContext *markContext = &gDvm.gcHeap->markContext;
726
727 /*
728 * All reachable objects have been marked.
729 * Any unmarked finalizable objects need to be finalized.
730 */
731
732 /* Create a table that the new pending refs will
733 * be added to.
734 */
Barry Hayesd4f78d32010-06-08 09:34:42 -0700735 if (!dvmHeapInitHeapRefTable(&newPendingRefs)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800736 //TODO: mark all finalizable refs and hope that
737 // we can schedule them next time. Watch out,
738 // because we may be expecting to free up space
739 // by calling finalizers.
740 LOGE_GC("dvmHeapScheduleFinalizations(): no room for "
741 "pending finalizations\n");
742 dvmAbort();
743 }
744
745 /* Walk through finalizableRefs and move any unmarked references
746 * to the list of new pending refs.
747 */
748 totalPendCount = 0;
749 while (finRefs != NULL) {
750 Object **gapRef;
751 size_t newPendCount = 0;
752
753 gapRef = ref = finRefs->refs.table;
754 lastRef = finRefs->refs.nextEntry;
755 while (ref < lastRef) {
Carl Shapiro6343bd02010-02-16 17:40:19 -0800756 if (!isMarked(*ref, markContext)) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800757 if (!dvmHeapAddToHeapRefTable(&newPendingRefs, *ref)) {
758 //TODO: add the current table and allocate
759 // a new, smaller one.
760 LOGE_GC("dvmHeapScheduleFinalizations(): "
761 "no room for any more pending finalizations: %zd\n",
762 dvmHeapNumHeapRefTableEntries(&newPendingRefs));
763 dvmAbort();
764 }
765 newPendCount++;
766 } else {
767 /* This ref is marked, so will remain on finalizableRefs.
768 */
769 if (newPendCount > 0) {
770 /* Copy it up to fill the holes.
771 */
772 *gapRef++ = *ref;
773 } else {
774 /* No holes yet; don't bother copying.
775 */
776 gapRef++;
777 }
778 }
779 ref++;
780 }
781 finRefs->refs.nextEntry = gapRef;
782 //TODO: if the table is empty when we're done, free it.
783 totalPendCount += newPendCount;
784 finRefs = finRefs->next;
785 }
786 LOGD_GC("dvmHeapScheduleFinalizations(): %zd finalizers triggered.\n",
787 totalPendCount);
788 if (totalPendCount == 0) {
789 /* No objects required finalization.
790 * Free the empty temporary table.
791 */
792 dvmClearReferenceTable(&newPendingRefs);
793 return;
794 }
795
796 /* Add the new pending refs to the main list.
797 */
798 if (!dvmHeapAddTableToLargeTable(&gDvm.gcHeap->pendingFinalizationRefs,
799 &newPendingRefs))
800 {
801 LOGE_GC("dvmHeapScheduleFinalizations(): can't insert new "
802 "pending finalizations\n");
803 dvmAbort();
804 }
805
806 //TODO: try compacting the main list with a memcpy loop
807
808 /* Mark the refs we just moved; we don't want them or their
809 * children to get swept yet.
810 */
811 ref = newPendingRefs.table;
812 lastRef = newPendingRefs.nextEntry;
813 assert(ref < lastRef);
814 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_FINALIZING, 0);
815 while (ref < lastRef) {
Barry Hayese1bccb92010-05-18 09:48:37 -0700816 assert(*ref != NULL);
817 markObject(*ref, markContext);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800818 ref++;
819 }
820 HPROF_CLEAR_GC_SCAN_STATE();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800821 processMarkStack(markContext);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800822 dvmSignalHeapWorker(false);
823}
824
825void dvmHeapFinishMarkStep()
826{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800827 GcMarkContext *markContext;
828
829 markContext = &gDvm.gcHeap->markContext;
830
831 /* The sweep step freed every object that appeared in the
832 * HeapSource bitmaps that didn't appear in the mark bitmaps.
833 * The new state of the HeapSource is exactly the final
834 * mark bitmaps, so swap them in.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800835 */
Carl Shapirof373efd2010-02-19 00:46:33 -0800836 dvmHeapSourceSwapBitmaps();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800837
Carl Shapirof373efd2010-02-19 00:46:33 -0800838 /* Clean up everything else associated with the marking process.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800839 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800840 destroyMarkStack(&markContext->stack);
841
Carl Shapirof373efd2010-02-19 00:46:33 -0800842 markContext->finger = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800843}
844
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800845static bool
846sweepBitmapCallback(size_t numPtrs, void **ptrs, const void *finger, void *arg)
847{
848 const ClassObject *const classJavaLangClass = gDvm.classJavaLangClass;
Barry Hayes5cbb2302010-02-02 14:07:37 -0800849 const bool overwriteFree = gDvm.overwriteFree;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800850 size_t i;
Barry Hayesdde8ab02009-05-20 12:10:36 -0700851 void **origPtrs = ptrs;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800852
853 for (i = 0; i < numPtrs; i++) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800854 Object *obj;
855
Carl Shapiro6343bd02010-02-16 17:40:19 -0800856 obj = (Object *)*ptrs++;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800857
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800858 /* This assumes that java.lang.Class will never go away.
859 * If it can, and we were the last reference to it, it
860 * could have already been swept. However, even in that case,
861 * gDvm.classJavaLangClass should still have a useful
862 * value.
863 */
864 if (obj->clazz == classJavaLangClass) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800865 /* dvmFreeClassInnards() may have already been called,
866 * but it's safe to call on the same ClassObject twice.
867 */
868 dvmFreeClassInnards((ClassObject *)obj);
869 }
870
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800871 /* Overwrite the to-be-freed object to make stale references
872 * more obvious.
873 */
Barry Hayes5cbb2302010-02-02 14:07:37 -0800874 if (overwriteFree) {
Barry Hayes2e3c3e12010-02-22 09:39:10 -0800875 int objlen;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800876 ClassObject *clazz = obj->clazz;
Barry Hayes2e3c3e12010-02-22 09:39:10 -0800877 objlen = dvmHeapSourceChunkSize(obj);
878 memset(obj, 0xa5, objlen);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800879 obj->clazz = (ClassObject *)((uintptr_t)clazz ^ 0xffffffff);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800880 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800881 }
Barry Hayesdde8ab02009-05-20 12:10:36 -0700882 // TODO: dvmHeapSourceFreeList has a loop, just like the above
883 // does. Consider collapsing the two loops to save overhead.
884 dvmHeapSourceFreeList(numPtrs, origPtrs);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800885
886 return true;
887}
888
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800889/* Returns true if the given object is unmarked. Ignores the low bits
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800890 * of the pointer because the intern table may set them.
891 */
892static int isUnmarkedObject(void *object)
893{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800894 return !isMarked((void *)((uintptr_t)object & ~(HB_OBJECT_ALIGNMENT-1)),
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800895 &gDvm.gcHeap->markContext);
896}
897
898/* Walk through the list of objects that haven't been
899 * marked and free them.
900 */
901void
Carl Shapirod25566d2010-03-11 20:39:47 -0800902dvmHeapSweepUnmarkedObjects(GcMode mode, int *numFreed, size_t *sizeFreed)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800903{
Carl Shapirof373efd2010-02-19 00:46:33 -0800904 HeapBitmap markBits[HEAP_SOURCE_MAX_HEAP_COUNT];
Carl Shapirod77f7fd2010-04-05 19:23:31 -0700905 HeapBitmap liveBits[HEAP_SOURCE_MAX_HEAP_COUNT];
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800906 size_t origObjectsAllocated;
907 size_t origBytesAllocated;
Carl Shapirod25566d2010-03-11 20:39:47 -0800908 size_t numBitmaps, numSweepBitmaps;
Barry Hayese168ebd2010-05-07 09:19:46 -0700909 size_t i;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800910
911 /* All reachable objects have been marked.
912 * Detach any unreachable interned strings before
913 * we sweep.
914 */
915 dvmGcDetachDeadInternedStrings(isUnmarkedObject);
916
917 /* Free any known objects that are not marked.
918 */
919 origObjectsAllocated = dvmHeapSourceGetValue(HS_OBJECTS_ALLOCATED, NULL, 0);
920 origBytesAllocated = dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
921
Carl Shapiro5a6071b2010-01-07 21:35:50 -0800922 dvmSweepMonitorList(&gDvm.monitorList, isUnmarkedObject);
923
Carl Shapirof373efd2010-02-19 00:46:33 -0800924 numBitmaps = dvmHeapSourceGetNumHeaps();
Carl Shapirod77f7fd2010-04-05 19:23:31 -0700925 dvmHeapSourceGetObjectBitmaps(liveBits, markBits, numBitmaps);
Carl Shapirod25566d2010-03-11 20:39:47 -0800926 if (mode == GC_PARTIAL) {
927 numSweepBitmaps = 1;
Carl Shapirod77f7fd2010-04-05 19:23:31 -0700928 assert((uintptr_t)gDvm.gcHeap->markContext.immuneLimit == liveBits[0].base);
Carl Shapirod25566d2010-03-11 20:39:47 -0800929 } else {
930 numSweepBitmaps = numBitmaps;
931 }
Barry Hayese168ebd2010-05-07 09:19:46 -0700932 for (i = 0; i < numSweepBitmaps; i++) {
933 dvmHeapBitmapXorWalk(&markBits[i], &liveBits[i],
934 sweepBitmapCallback, NULL);
935 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800936
937 *numFreed = origObjectsAllocated -
938 dvmHeapSourceGetValue(HS_OBJECTS_ALLOCATED, NULL, 0);
939 *sizeFreed = origBytesAllocated -
940 dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
941
942#ifdef WITH_PROFILER
943 if (gDvm.allocProf.enabled) {
944 gDvm.allocProf.freeCount += *numFreed;
945 gDvm.allocProf.freeSize += *sizeFreed;
946 }
947#endif
948}