blob: 4f32498cbb30c67f2bed413c867096da88221255 [file] [log] [blame]
Carl Shapirod28668c2010-04-15 16:10:00 -07001/*
2 * Copyright (C) 2009 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 <errno.h>
18#include <limits.h>
19#include <sys/mman.h>
20
21#include "Dalvik.h"
22#include "alloc/Heap.h"
23#include "alloc/HeapBitmap.h"
24#include "alloc/HeapInternal.h"
25#include "alloc/HeapSource.h"
26#include "alloc/Verify.h"
27#include "alloc/clz.h"
28
29/*
30 * A "mostly copying", generational, garbage collector.
31 *
32 * TODO: we allocate our own contiguous tract of page frames to back
33 * object allocations. To cooperate with other heaps active in the
34 * virtual machine we need to move the responsibility of allocating
35 * pages someplace outside of this code.
36 *
37 * The other major data structures that maintain the state of the heap
38 * are the block space table and the block queue.
39 *
40 * The block space table records the state of a block. We must track
41 * whether a block is:
42 *
43 * - Free or allocated in some space.
44 *
45 * - If the block holds part of a large object allocation, whether the
46 * block is the initial or a continued block of the allocation.
47 *
48 * - Whether the block is pinned, that is to say whether at least one
49 * object in the block must remain stationary. Only needed during a
50 * GC.
51 *
52 * - Which space the object belongs to. At present this means
53 * from-space or to-space.
54 *
55 * The block queue is used during garbage collection. Unlike Cheney's
56 * algorithm, from-space and to-space are not contiguous. Therefore,
57 * one cannot maintain the state of the copy with just two pointers.
58 * The block queue exists to thread lists of blocks from the various
59 * spaces together.
60 *
61 * Additionally, we record the free space frontier of the heap, as
62 * well as the address of the first object within a block, which is
63 * required to copy objects following a large object (not currently
64 * implemented). This is stored in the heap source structure. This
65 * should be moved elsewhere to support in-line allocations from Java
66 * threads.
67 *
68 * Allocation requests are satisfied by reserving storage from one or
69 * more contiguous blocks. Objects that are small enough to fit
70 * inside a block are packed together within a block. Objects that
71 * are larger than a block are allocated from contiguous sequences of
72 * blocks. When half the available blocks are filled, a garbage
73 * collection occurs. We "flip" spaces (exchange from- and to-space),
74 * copy live objects into to space, and perform pointer adjustment.
75 *
76 * Copying is made more complicated by the requirement that some
77 * objects must not be moved. This property is known as "pinning".
78 * These objects must be dealt with specially. We use Bartlett's
79 * scheme; blocks containing such objects are grayed (promoted) at the
80 * start of a garbage collection. By virtue of this trick, marking
81 * from the roots proceeds as usual but all objects on those pages are
82 * considered promoted and therefore not moved.
83 *
84 * TODO: there is sufficient information within the garbage collector
85 * to implement Attardi's scheme for evacuating unpinned objects from
86 * a page that is otherwise pinned. This would eliminate false
87 * retention caused by the large pinning granularity.
88 *
89 * We need a scheme for medium and large objects. Ignore that for
90 * now, we can return to this later.
91 *
92 * Eventually we need to worry about promoting objects out of the
93 * copy-collected heap (tenuring) into a less volatile space. Copying
94 * may not always be the best policy for such spaces. We should
95 * consider a variant of mark, sweep, compact.
96 *
97 * The block scheme allows us to use VM page faults to maintain a
98 * write barrier. Consider having a special leaf state for a page.
99 *
100 * Bibliography:
101 *
102 * C. J. Cheney. 1970. A non-recursive list compacting
103 * algorithm. CACM. 13-11 pp677--678.
104 *
105 * Joel F. Bartlett. 1988. Compacting Garbage Collection with
106 * Ambiguous Roots. Digital Equipment Corporation.
107 *
108 * Joel F. Bartlett. 1989. Mostly-Copying Garbage Collection Picks Up
109 * Generations and C++. Digital Equipment Corporation.
110 *
111 * G. May Yip. 1991. Incremental, Generational Mostly-Copying Garbage
112 * Collection in Uncooperative Environments. Digital Equipment
113 * Corporation.
114 *
115 * Giuseppe Attardi, Tito Flagella. 1994. A Customisable Memory
116 * Management Framework. TR-94-010
117 *
118 * Giuseppe Attardi, Tito Flagella, Pietro Iglio. 1998. A customisable
119 * memory management framework for C++. Software -- Practice and
120 * Experience. 28(11), 1143-1183.
121 *
122 */
123
124#define ARRAYSIZE(x) (sizeof(x) / sizeof(x[0]))
125
126#if 1
127#define LOG_ALLOC LOGI
128#define LOG_SCAVENGE LOGI
129#define LOG_TRANSPORT LOGI
130#define LOG_PROMOTE LOGI
131#define LOG_VERIFY LOGI
132#else
133#define LOG_ALLOC(...) ((void *)0)
134#define LOG_SCAVENGE(...) ((void *)0)
135#define LOG_TRANSPORT(...) ((void *)0)
136#define LOG_PROMOTE(...) ((void *)0)
137#define LOG_VERIFY(...) ((void *)0)
138#endif
139
140static void enqueueBlock(HeapSource *heapSource, size_t block);
141static size_t scavengeReference(Object **obj);
142static void verifyReference(const void *obj);
143static void printHeapBitmap(const HeapBitmap *bitmap);
144static void printHeapBitmapSxS(const HeapBitmap *b1, const HeapBitmap *b2);
145static bool isToSpace(const void *addr);
146static bool isFromSpace(const void *addr);
147static size_t sumHeapBitmap(const HeapBitmap *bitmap);
148static size_t scavengeDataObject(DataObject *obj);
149static DataObject *transportDataObject(const DataObject *fromObj);
150
151/*
152 * We use 512-byte blocks.
153 */
154enum { BLOCK_SHIFT = 9 };
155enum { BLOCK_SIZE = 1 << BLOCK_SHIFT };
156
157/*
158 * Space identifiers, stored into the blockSpace array.
159 */
160enum {
161 BLOCK_FREE = 0,
162 BLOCK_FROM_SPACE = 1,
163 BLOCK_TO_SPACE = 2,
164 BLOCK_CONTINUED = 7
165};
166
167/*
168 * Alignment for all allocations, in bytes.
169 */
170enum { ALLOC_ALIGNMENT = 8 };
171
172/*
173 * Sentinel value for the queue end.
174 */
175#define QUEUE_TAIL (~(size_t)0)
176
177struct HeapSource {
178
179 /* The base address of backing store. */
180 u1 *blockBase;
181
182 /* Total number of blocks available for allocation. */
183 size_t totalBlocks;
184 size_t allocBlocks;
185
186 /*
187 * The scavenger work queue. Implemented as an array of index
188 * values into the queue.
189 */
190 size_t *blockQueue;
191
192 /*
193 * Base and limit blocks. Basically the shifted start address of
194 * the block. We convert blocks to a relative number when
195 * indexing in the block queue. TODO: make the block queue base
196 * relative rather than the index into the block queue.
197 */
198 size_t baseBlock, limitBlock;
199
200 size_t queueHead;
201 size_t queueTail;
202 size_t queueSize;
203
204 /* The space of the current block 0 (free), 1 or 2. */
205 char *blockSpace;
206
207 /* Start of free space in the current block. */
208 u1 *allocPtr;
209 /* Exclusive limit of free space in the current block. */
210 u1 *allocLimit;
211
212 HeapBitmap allocBits;
213
214 /*
215 * Singly-linked lists of live Reference objects. Built when
216 * scavenging, threaded through the Reference.vmData field.
217 */
218 DataObject *softReferenceList;
219 DataObject *weakReferenceList;
220 DataObject *phantomReferenceList;
221
222 /*
223 * The starting size of the heap. This value is the same as the
224 * value provided to the -Xms flag.
225 */
226 size_t minimumSize;
227
228 /*
229 * The maximum size of the heap. This value is the same as the
230 * -Xmx flag.
231 */
232 size_t maximumSize;
233
234 /*
235 * The current, committed size of the heap. At present, this is
236 * equivalent to the maximumSize.
237 */
238 size_t currentSize;
239
240 size_t bytesAllocated;
241};
242
243static unsigned long alignDown(unsigned long x, unsigned long n)
244{
245 return x & -n;
246}
247
248static unsigned long alignUp(unsigned long x, unsigned long n)
249{
250 return alignDown(x + (n - 1), n);
251}
252
253static void describeBlocks(const HeapSource *heapSource)
254{
255 size_t i;
256
257 for (i = 0; i < heapSource->totalBlocks; ++i) {
258 if ((i % 32) == 0) putchar('\n');
259 printf("%d ", heapSource->blockSpace[i]);
260 }
261 putchar('\n');
262}
263
264/*
265 * Virtual memory interface.
266 */
267
268static void *virtualAlloc(size_t length)
269{
270 void *addr;
271 int flags, prot;
272
273 flags = MAP_PRIVATE | MAP_ANONYMOUS;
274 prot = PROT_READ | PROT_WRITE;
275 addr = mmap(NULL, length, prot, flags, -1, 0);
276 if (addr == MAP_FAILED) {
277 LOGE_HEAP("mmap: %s", strerror(errno));
278 addr = NULL;
279 }
280 return addr;
281}
282
283static void virtualFree(void *addr, size_t length)
284{
285 int res;
286
287 assert(addr != NULL);
288 assert((uintptr_t)addr % SYSTEM_PAGE_SIZE == 0);
289 res = munmap(addr, length);
290 if (res == -1) {
291 LOGE_HEAP("munmap: %s", strerror(errno));
292 }
293}
294
295static int isValidAddress(const HeapSource *heapSource, const u1 *addr)
296{
297 size_t block;
298
299 block = (uintptr_t)addr >> BLOCK_SHIFT;
300 return heapSource->baseBlock <= block &&
301 heapSource->limitBlock > block;
302}
303
304/*
305 * Iterate over the block map looking for a contiguous run of free
306 * blocks.
307 */
308static void *allocateBlocks(HeapSource *heapSource, size_t blocks)
309{
310 void *addr;
311 size_t allocBlocks, totalBlocks;
312 size_t i, j;
313
314 allocBlocks = heapSource->allocBlocks;
315 totalBlocks = heapSource->totalBlocks;
316 /* Check underflow. */
317 assert(blocks != 0);
318 /* Check overflow. */
319 if (allocBlocks + blocks > totalBlocks / 2) {
320 return NULL;
321 }
322 /* Scan block map. */
323 for (i = 0; i < totalBlocks; ++i) {
324 /* Check fit. */
325 for (j = 0; j < blocks; ++j) { /* runs over totalBlocks */
326 if (heapSource->blockSpace[i+j] != BLOCK_FREE) {
327 break;
328 }
329 }
330 /* No fit? */
331 if (j != blocks) {
332 i += j;
333 continue;
334 }
335 /* Fit, allocate. */
336 heapSource->blockSpace[i] = BLOCK_TO_SPACE; /* why to-space? */
337 for (j = 1; j < blocks; ++j) {
338 heapSource->blockSpace[i+j] = BLOCK_CONTINUED;
339 }
340 heapSource->allocBlocks += blocks;
341 addr = &heapSource->blockBase[i*BLOCK_SIZE];
342 memset(addr, 0, blocks*BLOCK_SIZE);
343 /* Collecting? */
344 if (heapSource->queueHead != QUEUE_TAIL) {
345 LOG_ALLOC("allocateBlocks allocBlocks=%zu,block#=%zu", heapSource->allocBlocks, i);
346 /*
347 * This allocated was on behalf of the transporter when it
348 * shaded a white object gray. We enqueue the block so
349 * the scavenger can further shade the gray objects black.
350 */
351 enqueueBlock(heapSource, i);
352 }
353
354 return addr;
355 }
356 /* Insufficient space, fail. */
357 LOGE("Insufficient space, %zu blocks, %zu blocks allocated and %zu bytes allocated",
358 heapSource->totalBlocks,
359 heapSource->allocBlocks,
360 heapSource->bytesAllocated);
361 return NULL;
362}
363
364/* Converts an absolute address to a relative block number. */
365static size_t addressToBlock(const HeapSource *heapSource, const void *addr)
366{
367 assert(heapSource != NULL);
368 assert(isValidAddress(heapSource, addr));
369 return (((uintptr_t)addr) >> BLOCK_SHIFT) - heapSource->baseBlock;
370}
371
372/* Converts a relative block number to an absolute address. */
373static u1 *blockToAddress(const HeapSource *heapSource, size_t block)
374{
375 u1 *addr;
376
377 addr = (u1 *) (((uintptr_t) heapSource->baseBlock + block) * BLOCK_SIZE);
378 assert(isValidAddress(heapSource, addr));
379 return addr;
380}
381
382static void clearBlock(HeapSource *heapSource, size_t block)
383{
384 u1 *addr;
385 size_t i;
386
387 assert(heapSource != NULL);
388 assert(block < heapSource->totalBlocks);
389 addr = heapSource->blockBase + block*BLOCK_SIZE;
390 memset(addr, 0xCC, BLOCK_SIZE);
391 for (i = 0; i < BLOCK_SIZE; i += 8) {
392 dvmHeapBitmapClearObjectBit(&heapSource->allocBits, addr + i);
393 }
394}
395
396static void clearFromSpace(HeapSource *heapSource)
397{
398 size_t i, count;
399
400 assert(heapSource != NULL);
401 i = count = 0;
402 while (i < heapSource->totalBlocks) {
403 if (heapSource->blockSpace[i] != BLOCK_FROM_SPACE) {
404 ++i;
405 continue;
406 }
407 heapSource->blockSpace[i] = BLOCK_FREE;
408 clearBlock(heapSource, i);
409 ++i;
410 ++count;
411 while (i < heapSource->totalBlocks &&
412 heapSource->blockSpace[i] == BLOCK_CONTINUED) {
413 heapSource->blockSpace[i] = BLOCK_FREE;
414 clearBlock(heapSource, i);
415 ++i;
416 ++count;
417 }
418 }
419 LOGI("freed %zu blocks (%zu bytes)", count, count*BLOCK_SIZE);
420}
421
422/*
423 * Appends the given block to the block queue. The block queue is
424 * processed in-order by the scavenger.
425 */
426static void enqueueBlock(HeapSource *heapSource, size_t block)
427{
428 assert(heapSource != NULL);
429 assert(block < heapSource->totalBlocks);
430 if (heapSource->queueHead != QUEUE_TAIL) {
431 heapSource->blockQueue[heapSource->queueTail] = block;
432 } else {
433 heapSource->queueHead = block;
434 }
435 heapSource->blockQueue[block] = QUEUE_TAIL;
436 heapSource->queueTail = block;
437 ++heapSource->queueSize;
438}
439
440/*
441 * Grays all objects within the block corresponding to the given
442 * address.
443 */
444static void promoteBlockByAddr(HeapSource *heapSource, const void *addr)
445{
446 size_t block;
447
448 block = addressToBlock(heapSource, (const u1 *)addr);
449 if (heapSource->blockSpace[block] != BLOCK_TO_SPACE) {
450 // LOGI("promoting block %zu %d @ %p", block, heapSource->blockSpace[block], obj);
451 heapSource->blockSpace[block] = BLOCK_TO_SPACE;
452 enqueueBlock(heapSource, block);
453 /* TODO(cshapiro): count continued blocks?*/
454 heapSource->allocBlocks += 1;
455 } else {
456 // LOGI("NOT promoting block %zu %d @ %p", block, heapSource->blockSpace[block], obj);
457 }
458}
459
460GcHeap *dvmHeapSourceStartup(size_t startSize, size_t absoluteMaxSize)
461{
462 GcHeap* gcHeap;
463 HeapSource *heapSource;
464
465 assert(startSize <= absoluteMaxSize);
466
467 heapSource = malloc(sizeof(*heapSource));
468 assert(heapSource != NULL);
469 memset(heapSource, 0, sizeof(*heapSource));
470
471 heapSource->minimumSize = alignUp(startSize, BLOCK_SIZE);
472 heapSource->maximumSize = alignUp(absoluteMaxSize, BLOCK_SIZE);
473
474 heapSource->currentSize = heapSource->maximumSize;
475
476 /* Allocate underlying storage for blocks. */
477 heapSource->blockBase = virtualAlloc(heapSource->maximumSize);
478 assert(heapSource->blockBase != NULL);
479 heapSource->baseBlock = (uintptr_t) heapSource->blockBase >> BLOCK_SHIFT;
480 heapSource->limitBlock = ((uintptr_t) heapSource->blockBase + heapSource->maximumSize) >> BLOCK_SHIFT;
481
482 heapSource->allocBlocks = 0;
483 heapSource->totalBlocks = (heapSource->limitBlock - heapSource->baseBlock);
484
485 assert(heapSource->totalBlocks = heapSource->maximumSize / BLOCK_SIZE);
486
487 {
488 size_t size = sizeof(heapSource->blockQueue[0]);
489 heapSource->blockQueue = malloc(heapSource->totalBlocks*size);
490 assert(heapSource->blockQueue != NULL);
491 memset(heapSource->blockQueue, 0xCC, heapSource->totalBlocks*size);
492 heapSource->queueHead = QUEUE_TAIL;
493 }
494
495 /* Byte indicating space residence or free status of block. */
496 {
497 size_t size = sizeof(heapSource->blockSpace[0]);
498 heapSource->blockSpace = malloc(heapSource->totalBlocks*size);
499 assert(heapSource->blockSpace != NULL);
500 memset(heapSource->blockSpace, 0, heapSource->totalBlocks*size);
501 }
502
503 dvmHeapBitmapInit(&heapSource->allocBits,
504 heapSource->blockBase,
505 heapSource->maximumSize,
506 "blockBase");
507
508 /* Initialize allocation pointers. */
509 heapSource->allocPtr = allocateBlocks(heapSource, 1);
510 heapSource->allocLimit = heapSource->allocPtr + BLOCK_SIZE;
511
512 gcHeap = malloc(sizeof(*gcHeap));
513 assert(gcHeap != NULL);
514 memset(gcHeap, 0, sizeof(*gcHeap));
515 gcHeap->heapSource = heapSource;
516
517 return gcHeap;
518}
519
520/*
521 * Perform any required heap initializations after forking from the
522 * zygote process. This is a no-op for the time being. Eventually
523 * this will demarcate the shared region of the heap.
524 */
525bool dvmHeapSourceStartupAfterZygote(void)
526{
527 return true;
528}
529
530bool dvmHeapSourceStartupBeforeFork(void)
531{
532 assert(!"implemented");
533 return false;
534}
535
536void dvmHeapSourceShutdown(GcHeap **gcHeap)
537{
538 if (*gcHeap == NULL || (*gcHeap)->heapSource == NULL)
539 return;
540 virtualFree((*gcHeap)->heapSource->blockBase,
541 (*gcHeap)->heapSource->maximumSize);
542 free((*gcHeap)->heapSource);
543 (*gcHeap)->heapSource = NULL;
544 free(*gcHeap);
545 *gcHeap = NULL;
546}
547
548size_t dvmHeapSourceGetValue(enum HeapSourceValueSpec spec,
549 size_t perHeapStats[],
550 size_t arrayLen)
551{
552 HeapSource *heapSource;
553 size_t value;
554
555 heapSource = gDvm.gcHeap->heapSource;
556 switch (spec) {
557 case HS_EXTERNAL_BYTES_ALLOCATED:
558 value = 0;
559 break;
560 case HS_EXTERNAL_LIMIT:
561 value = 0;
562 break;
563 case HS_FOOTPRINT:
564 value = heapSource->maximumSize;
565 break;
566 case HS_ALLOWED_FOOTPRINT:
567 value = heapSource->maximumSize;
568 break;
569 case HS_BYTES_ALLOCATED:
570 value = heapSource->bytesAllocated;
571 break;
572 case HS_OBJECTS_ALLOCATED:
573 value = sumHeapBitmap(&heapSource->allocBits);
574 break;
575 default:
576 assert(!"implemented");
577 value = 0;
578 }
579 if (perHeapStats) {
580 *perHeapStats = value;
581 }
582 return value;
583}
584
585/*
586 * Performs a shallow copy of the allocation bitmap into the given
587 * vector of heap bitmaps.
588 */
589void dvmHeapSourceGetObjectBitmaps(HeapBitmap objBits[], HeapBitmap markBits[],
590 size_t numHeaps)
591{
592 assert(!"implemented");
593}
594
595HeapBitmap *dvmHeapSourceGetLiveBits(void)
596{
597 assert(!"implemented");
598 return NULL;
599}
600
601/*
602 * Allocate the specified number of bytes from the heap. The
603 * allocation cursor points into a block of free storage. If the
604 * given allocation fits in the remaining space of the block, we
605 * advance the cursor and return a pointer to the free storage. If
606 * the allocation cannot fit in the current block but is smaller than
607 * a block we request a new block and allocate from it instead. If
608 * the allocation is larger than a block we must allocate from a span
609 * of contiguous blocks.
610 */
611void *dvmHeapSourceAlloc(size_t length)
612{
613 HeapSource *heapSource;
614 unsigned char *addr;
615 size_t aligned, available, blocks;
616
617 heapSource = gDvm.gcHeap->heapSource;
618 assert(heapSource != NULL);
619 assert(heapSource->allocPtr != NULL);
620 assert(heapSource->allocLimit != NULL);
621
622 aligned = alignUp(length, ALLOC_ALIGNMENT);
623 available = heapSource->allocLimit - heapSource->allocPtr;
624
625 /* Try allocating inside the current block. */
626 if (aligned <= available) {
627 addr = heapSource->allocPtr;
628 heapSource->allocPtr += aligned;
629 heapSource->bytesAllocated += aligned;
630 dvmHeapBitmapSetObjectBit(&heapSource->allocBits, addr);
631 return addr;
632 }
633
634 /* Try allocating in a new block. */
635 if (aligned <= BLOCK_SIZE) {
636 addr = allocateBlocks(heapSource, 1);
637 if (addr != NULL) {
638 heapSource->allocLimit = addr + BLOCK_SIZE;
639 heapSource->allocPtr = addr + aligned;
640 heapSource->bytesAllocated += aligned;
641 dvmHeapBitmapSetObjectBit(&heapSource->allocBits, addr);
642 /* TODO(cshapiro): pad out the current block. */
643 }
644 return addr;
645 }
646
647 /* Try allocating in a span of blocks. */
648 blocks = alignUp(aligned, BLOCK_SIZE) / BLOCK_SIZE;
649
650 addr = allocateBlocks(heapSource, blocks);
651 /* Propagate failure upward. */
652 if (addr != NULL) {
653 heapSource->bytesAllocated += aligned;
654 dvmHeapBitmapSetObjectBit(&heapSource->allocBits, addr);
655 /* TODO(cshapiro): pad out free space in the last block. */
656 }
657 return addr;
658}
659
660void *dvmHeapSourceAllocAndGrow(size_t size)
661{
662 return dvmHeapSourceAlloc(size);
663}
664
665/* TODO: refactor along with dvmHeapSourceAlloc */
666void *allocateGray(size_t size)
667{
668 assert(gDvm.gcHeap->heapSource->queueHead != QUEUE_TAIL);
669 return dvmHeapSourceAlloc(size);
670}
671
672/*
673 * Returns true if the given address is within the heap and points to
674 * the header of a live object.
675 */
676bool dvmHeapSourceContains(const void *addr)
677{
678 HeapSource *heapSource;
679 HeapBitmap *bitmap;
680
681 heapSource = gDvm.gcHeap->heapSource;
682 bitmap = &heapSource->allocBits;
Carl Shapirodc1e4f12010-05-01 22:27:56 -0700683 if (!dvmHeapBitmapCoversAddress(bitmap, addr)) {
684 return false;
685 } else {
686 return dvmHeapBitmapIsObjectBitSet(bitmap, addr);
687 }
Carl Shapirod28668c2010-04-15 16:10:00 -0700688}
689
690bool dvmHeapSourceGetPtrFlag(const void *ptr, enum HeapSourcePtrFlag flag)
691{
692 assert(!"implemented");
693 return false;
694}
695
696size_t dvmHeapSourceChunkSize(const void *ptr)
697{
698 assert(!"implemented");
699 return 0;
700}
701
702size_t dvmHeapSourceFootprint(void)
703{
704 assert(!"implemented");
705 return 0;
706}
707
708/*
709 * Returns the "ideal footprint" which appears to be the number of
710 * bytes currently committed to the heap. This starts out at the
711 * start size of the heap and grows toward the maximum size.
712 */
713size_t dvmHeapSourceGetIdealFootprint(void)
714{
715 return gDvm.gcHeap->heapSource->currentSize;
716}
717
718float dvmGetTargetHeapUtilization(void)
719{
720 assert(!"implemented");
721 return 0.0f;
722}
723
724void dvmSetTargetHeapUtilization(float newTarget)
725{
726 assert(!"implemented");
727}
728
729size_t dvmMinimumHeapSize(size_t size, bool set)
730{
731 return gDvm.gcHeap->heapSource->minimumSize;
732}
733
734/*
735 * Expands the size of the heap after a collection. At present we
736 * commit the pages for maximum size of the heap so this routine is
737 * just a no-op. Eventually, we will either allocate or commit pages
738 * on an as-need basis.
739 */
740void dvmHeapSourceGrowForUtilization(void)
741{
742 /* do nothing */
743}
744
745void dvmHeapSourceTrim(size_t bytesTrimmed[], size_t arrayLen)
746{
747 /* do nothing */
748}
749
750void dvmHeapSourceWalk(void (*callback)(const void *chunkptr, size_t chunklen,
751 const void *userptr, size_t userlen,
752 void *arg),
753 void *arg)
754{
755 assert(!"implemented");
756}
757
758size_t dvmHeapSourceGetNumHeaps(void)
759{
760 return 1;
761}
762
763bool dvmTrackExternalAllocation(size_t n)
764{
765 assert(!"implemented");
766 return false;
767}
768
769void dvmTrackExternalFree(size_t n)
770{
771 assert(!"implemented");
772}
773
774size_t dvmGetExternalBytesAllocated(void)
775{
776 assert(!"implemented");
777 return 0;
778}
779
780void dvmHeapSourceFlip(void)
781{
782 HeapSource *heapSource;
783 size_t i;
784
785 heapSource = gDvm.gcHeap->heapSource;
786
787 /* Reset the block queue. */
788 heapSource->allocBlocks = 0;
789 heapSource->queueSize = 0;
790 heapSource->queueHead = QUEUE_TAIL;
791
792 /* Hack: reset the reference lists. */
793 /* TODO(cshapiro): implement reference object processing. */
794 heapSource->softReferenceList = NULL;
795 heapSource->weakReferenceList = NULL;
796 heapSource->phantomReferenceList = NULL;
797
798 /* TODO(cshapiro): pad the current (prev) block. */
799
800 heapSource->allocPtr = NULL;
801 heapSource->allocLimit = NULL;
802
803 /* Whiten all allocated blocks. */
804 for (i = 0; i < heapSource->totalBlocks; ++i) {
805 if (heapSource->blockSpace[i] == BLOCK_TO_SPACE) {
806 heapSource->blockSpace[i] = BLOCK_FROM_SPACE;
807 }
808 }
809}
810
811static void room(size_t *alloc, size_t *avail, size_t *total)
812{
813 HeapSource *heapSource;
814 size_t i;
815
816 heapSource = gDvm.gcHeap->heapSource;
817 *total = heapSource->totalBlocks*BLOCK_SIZE;
818 *alloc = heapSource->allocBlocks*BLOCK_SIZE;
819 *avail = *total - *alloc;
820}
821
822static bool isSpaceInternal(u1 *addr, int space)
823{
824 HeapSource *heapSource;
825 u1 *base, *limit;
826 size_t offset;
827 char space2;
828
829 heapSource = gDvm.gcHeap->heapSource;
830 base = heapSource->blockBase;
831 assert(addr >= base);
832 limit = heapSource->blockBase + heapSource->maximumSize;
833 assert(addr < limit);
834 offset = addr - base;
835 space2 = heapSource->blockSpace[offset >> BLOCK_SHIFT];
836 return space == space2;
837}
838
839static bool isFromSpace(const void *addr)
840{
841 return isSpaceInternal((u1 *)addr, BLOCK_FROM_SPACE);
842}
843
844static bool isToSpace(const void *addr)
845{
846 return isSpaceInternal((u1 *)addr, BLOCK_TO_SPACE);
847}
848
849/*
850 * Notifies the collector that the object at the given address must
851 * remain stationary during the current collection.
852 */
853static void pinObject(const Object *obj)
854{
855 promoteBlockByAddr(gDvm.gcHeap->heapSource, obj);
856}
857
858static void printHeapBitmap(const HeapBitmap *bitmap)
859{
860 const char *cp;
861 size_t i, length;
862
863 length = bitmap->bitsLen >> 2;
864 fprintf(stderr, "%p", bitmap->bits);
865 for (i = 0; i < length; ++i) {
866 fprintf(stderr, " %lx", bitmap->bits[i]);
867 fputc('\n', stderr);
868 }
869}
870
871static void printHeapBitmapSxS(const HeapBitmap *b1, const HeapBitmap *b2)
872{
873 uintptr_t addr;
874 size_t i, length;
875
876 assert(b1->base == b2->base);
877 assert(b1->bitsLen == b2->bitsLen);
878 addr = b1->base;
879 length = b1->bitsLen >> 2;
880 for (i = 0; i < length; ++i) {
881 int diff = b1->bits[i] == b2->bits[i];
882 fprintf(stderr, "%08x %08lx %08lx %d\n",
883 addr, b1->bits[i], b2->bits[i], diff);
884 addr += sizeof(*b1->bits)*CHAR_BIT;
885 }
886}
887
888static size_t sumHeapBitmap(const HeapBitmap *bitmap)
889{
890 const char *cp;
891 size_t i, sum;
892
893 sum = 0;
894 for (i = 0; i < bitmap->bitsLen >> 2; ++i) {
895 sum += dvmClzImpl(bitmap->bits[i]);
896 }
897 return sum;
898}
899
900/*
901 * Miscellaneous functionality.
902 */
903
904static int isForward(const void *addr)
905{
906 return (uintptr_t)addr & 0x1;
907}
908
909static void setForward(const void *toObj, void *fromObj)
910{
911 *(unsigned long *)fromObj = (uintptr_t)toObj | 0x1;
912}
913
914static void* getForward(const void *fromObj)
915{
916 return (void *)((uintptr_t)fromObj & ~0x1);
917}
918
919/* Beware, uses the same encoding as a forwarding pointers! */
920static int isPermanentString(const StringObject *obj) {
921 return (uintptr_t)obj & 0x1;
922}
923
924static void* getPermanentString(const StringObject *obj)
925{
926 return (void *)((uintptr_t)obj & ~0x1);
927}
928
929
930/*
931 * Scavenging and transporting routines follow. A transporter grays
932 * an object. A scavenger blackens an object. We define these
933 * routines for each fundamental object type. Dispatch is performed
934 * in scavengeObject.
935 */
936
937/*
938 * Class object scavenging and transporting.
939 */
940
941static ClassObject *transportClassObject(const ClassObject *fromObj)
942{
943 ClassObject *toObj;
944 size_t length;
945
946 LOG_TRANSPORT("transportClassObject(fromObj=%p)", fromObj);
947 length = dvmClassObjectSize(fromObj); /* TODO: hash code */
948 assert(length != 0);
949 toObj = allocateGray(length);
950 assert(toObj != NULL);
951 memcpy(toObj, fromObj, length);
952 LOG_TRANSPORT("transportClassObject: from %p to %p (%zu)", fromObj, toObj, length);
953 return toObj;
954}
955
956static size_t scavengeClassObject(ClassObject *obj)
957{
958 size_t size;
959 int i;
960
961 assert(obj != NULL);
962 LOG_SCAVENGE("scavengeClassObject(obj=%p)", obj);
963 /* Scavenge our class object. */
964 assert(obj->obj.clazz != NULL);
965 assert(obj->obj.clazz->descriptor != NULL);
966 assert(!strcmp(obj->obj.clazz->descriptor, "Ljava/lang/Class;"));
967 assert(obj->descriptor != NULL);
968 LOG_SCAVENGE("scavengeClassObject: descriptor='%s',vtableCount=%zu",
969 obj->descriptor, obj->vtableCount);
970 scavengeReference((Object **) obj);
971 /* Scavenge the array element class object. */
972 if (IS_CLASS_FLAG_SET(obj, CLASS_ISARRAY)) {
973 scavengeReference((Object **)(void *)&obj->elementClass);
974 }
975 /* Scavenge the superclass. */
976 scavengeReference((Object **)(void *)&obj->super);
977 /* Scavenge the class loader. */
978 scavengeReference(&obj->classLoader);
979 /* Scavenge static fields. */
980 for (i = 0; i < obj->sfieldCount; ++i) {
981 char ch = obj->sfields[i].field.signature[0];
982 if (ch == '[' || ch == 'L') {
983 scavengeReference((Object **)(void *)&obj->sfields[i].value.l);
984 }
985 }
986 /* Scavenge interface class objects. */
987 for (i = 0; i < obj->interfaceCount; ++i) {
988 scavengeReference((Object **) &obj->interfaces[i]);
989 }
990 size = dvmClassObjectSize(obj);
991 return size;
992}
993
994/*
995 * Array object scavenging.
996 */
997
998static ArrayObject *transportArrayObject(const ArrayObject *fromObj)
999{
1000 ArrayObject *toObj;
1001 size_t length;
1002
1003 LOG_TRANSPORT("transportArrayObject(fromObj=%p)", fromObj);
1004 length = dvmArrayObjectSize(fromObj);
1005 assert(length != 0);
1006 if (length >= BLOCK_SIZE) {
1007 LOGI("WARNING: LARGE ARRAY OBJECT %s", fromObj->obj.clazz->descriptor);
1008 }
1009 toObj = allocateGray(length);
1010 LOG_TRANSPORT("transportArrayObject: from %p to %p (%zu)", fromObj, toObj, length);
1011 assert(toObj != NULL);
1012 memcpy(toObj, fromObj, length);
1013 return toObj;
1014}
1015
1016static size_t scavengeArrayObject(ArrayObject *array)
1017{
1018 size_t i, length;
1019
1020 LOG_SCAVENGE("scavengeArrayObject(array=%p)", array);
1021 /* Scavenge the class object. */
1022 assert(isToSpace(array));
1023 assert(array != NULL);
1024 assert(array->obj.clazz != NULL);
1025 scavengeReference((Object **) array);
1026 length = dvmArrayObjectSize(array);
1027 /* Scavenge the array contents. */
1028 if (IS_CLASS_FLAG_SET(array->obj.clazz, CLASS_ISOBJECTARRAY)) {
1029 Object **contents = (Object **)array->contents;
1030 for (i = 0; i < array->length; ++i) {
1031 scavengeReference(&contents[i]);
1032 }
1033 }
1034 return length;
1035}
1036
1037/*
1038 * Reference object scavenging.
1039 */
1040
1041static int getReferenceFlags(const DataObject *obj)
1042{
1043 int flags;
1044
1045 flags = CLASS_ISREFERENCE |
1046 CLASS_ISWEAKREFERENCE |
1047 CLASS_ISPHANTOMREFERENCE;
1048 return GET_CLASS_FLAG_GROUP(obj->obj.clazz, flags);
1049}
1050
1051static int isReference(const DataObject *obj)
1052{
1053 return getReferenceFlags(obj) != 0;
1054}
1055
1056static int isSoftReference(const DataObject *obj)
1057{
1058 return getReferenceFlags(obj) == CLASS_ISREFERENCE;
1059}
1060
1061static int isWeakReference(const DataObject *obj)
1062{
1063 return getReferenceFlags(obj) & CLASS_ISWEAKREFERENCE;
1064}
1065
1066static bool isPhantomReference(const DataObject *obj)
1067{
1068 return getReferenceFlags(obj) & CLASS_ISPHANTOMREFERENCE;
1069}
1070
1071static void clearReference(DataObject *reference)
1072{
1073 size_t offset;
1074
1075 assert(isSoftReference(reference) || isWeakReference(reference));
1076 offset = gDvm.offJavaLangRefReference_referent;
1077 dvmSetFieldObject((Object *)reference, offset, NULL);
1078}
1079
1080static bool isReferentGray(const DataObject *reference)
1081{
1082 Object *obj;
1083 size_t offset;
1084
1085 assert(reference != NULL);
1086 assert(isSoftReference(reference) || isWeakReference(reference));
1087 offset = gDvm.offJavaLangRefReference_referent;
1088 obj = dvmGetFieldObject((Object *)reference, offset);
1089 return obj == NULL || isToSpace(obj);
1090}
1091
1092static void enqueueReference(HeapSource *heapSource, DataObject *reference)
1093{
1094 DataObject **queue;
1095 size_t offset;
1096
1097 LOGI("enqueueReference(heapSource=%p,reference=%p)", heapSource, reference);
1098 assert(heapSource != NULL);
1099 assert(reference != NULL);
1100 assert(isToSpace(reference));
1101 assert(isReference(reference));
1102 if (isSoftReference(reference)) {
1103 queue = &heapSource->softReferenceList;
1104 } else if (isWeakReference(reference)) {
1105 queue = &heapSource->weakReferenceList;
1106 } else if (isPhantomReference(reference)) {
1107 queue = &heapSource->phantomReferenceList;
1108 } else {
1109 assert(!"reached");
1110 queue = NULL;
1111 }
1112 offset = gDvm.offJavaLangRefReference_vmData;
1113 dvmSetFieldObject((Object *)reference, offset, (Object *)*queue);
1114 *queue = reference;
1115}
1116
1117static DataObject *transportReferenceObject(const DataObject *fromObj)
1118{
1119 assert(fromObj != NULL);
1120 LOG_TRANSPORT("transportReferenceObject(fromObj=%p)", fromObj);
1121 return transportDataObject(fromObj);
1122}
1123
1124/*
1125 * If a reference points to from-space and has been forwarded, we snap
1126 * the pointer to its new to-space address. If the reference points
1127 * to an unforwarded from-space address we must enqueue the reference
1128 * for later processing. TODO: implement proper reference processing
1129 * and move the referent scavenging elsewhere.
1130 */
1131static size_t scavengeReferenceObject(DataObject *obj)
1132{
1133 size_t length;
1134
1135 assert(obj != NULL);
1136 LOG_SCAVENGE("scavengeReferenceObject(obj=%p),'%s'", obj, obj->obj.clazz->descriptor);
1137 {
1138 /* Always scavenge the hidden Reference.referent field. */
1139 size_t offset = gDvm.offJavaLangRefReference_referent;
1140 void *addr = BYTE_OFFSET((Object *)obj, offset);
1141 Object **ref = (Object **)(void *)&((JValue *)addr)->l;
1142 scavengeReference(ref);
1143 }
1144 length = scavengeDataObject(obj);
1145 if (!isReferentGray(obj)) {
1146 assert(!"reached"); /* TODO(cshapiro): remove this */
1147 LOG_SCAVENGE("scavengeReferenceObject: enqueueing %p", obj);
1148 enqueueReference(gDvm.gcHeap->heapSource, obj);
1149 length = obj->obj.clazz->objectSize;
1150 }
1151 return length;
1152}
1153
1154/*
1155 * Data object scavenging.
1156 */
1157
1158static DataObject *transportDataObject(const DataObject *fromObj)
1159{
1160 DataObject *toObj;
1161 ClassObject *clazz;
1162 const char *name;
1163 size_t length;
1164 int flags;
1165
1166 assert(fromObj != NULL);
1167 assert(isFromSpace(fromObj));
1168 LOG_TRANSPORT("transportDataObject(fromObj=%p) allocBlocks=%zu", fromObj, gDvm.gcHeap->heapSource->allocBlocks);
1169 clazz = fromObj->obj.clazz;
1170 assert(clazz != NULL);
1171 length = clazz->objectSize;
1172 assert(length != 0);
1173 /* TODO(cshapiro): don't copy, re-map large data objects. */
1174 toObj = allocateGray(length);
1175 assert(toObj != NULL);
1176 assert(isToSpace(toObj));
1177 memcpy(toObj, fromObj, length);
1178 LOG_TRANSPORT("transportDataObject: from %p/%zu to %p/%zu (%zu)", fromObj, addressToBlock(gDvm.gcHeap->heapSource,fromObj), toObj, addressToBlock(gDvm.gcHeap->heapSource,toObj), length);
1179 return toObj;
1180}
1181
1182static size_t scavengeDataObject(DataObject *obj)
1183{
1184 ClassObject *clazz;
1185 size_t length;
1186 int i;
1187
1188 // LOGI("scavengeDataObject(obj=%p)", obj);
1189 assert(obj != NULL);
1190 assert(obj->obj.clazz != NULL);
1191 assert(obj->obj.clazz->objectSize != 0);
1192 assert(isToSpace(obj));
1193 /* Scavenge the class object. */
1194 clazz = obj->obj.clazz;
1195 scavengeReference((Object **) obj);
1196 length = obj->obj.clazz->objectSize;
1197 /* Scavenge instance fields. */
1198 if (clazz->refOffsets != CLASS_WALK_SUPER) {
1199 size_t refOffsets = clazz->refOffsets;
1200 while (refOffsets != 0) {
1201 size_t rshift = CLZ(refOffsets);
1202 size_t offset = CLASS_OFFSET_FROM_CLZ(rshift);
1203 Object **ref = (Object **)((u1 *)obj + offset);
1204 scavengeReference(ref);
1205 refOffsets &= ~(CLASS_HIGH_BIT >> rshift);
1206 }
1207 } else {
1208 for (; clazz != NULL; clazz = clazz->super) {
1209 InstField *field = clazz->ifields;
1210 for (i = 0; i < clazz->ifieldRefCount; ++i, ++field) {
1211 size_t offset = field->byteOffset;
1212 Object **ref = (Object **)((u1 *)obj + offset);
1213 scavengeReference(ref);
1214 }
1215 }
1216 }
1217 return length;
1218}
1219
1220/*
1221 * Generic reference scavenging.
1222 */
1223
1224/*
1225 * Given a reference to an object, the scavenge routine will gray the
1226 * reference. Any objects pointed to by the scavenger object will be
1227 * transported to new space and a forwarding pointer will be installed
1228 * in the header of the object.
1229 */
1230
1231/*
1232 * Blacken the given pointer. If the pointer is in from space, it is
1233 * transported to new space. If the object has a forwarding pointer
1234 * installed it has already been transported and the referent is
1235 * snapped to the new address.
1236 */
1237static size_t scavengeReference(Object **obj)
1238{
1239 ClassObject *clazz;
1240 uintptr_t word;
1241
1242 assert(obj);
1243
1244 if (*obj == NULL) goto exit;
1245
1246 assert(dvmIsValidObject(*obj));
1247
1248 /* The entire block is black. */
1249 if (isToSpace(*obj)) {
1250 LOG_SCAVENGE("scavengeReference skipping pinned object @ %p", *obj);
1251 goto exit;
1252 }
1253 LOG_SCAVENGE("scavengeReference(*obj=%p)", *obj);
1254
1255 assert(isFromSpace(*obj));
1256
1257 clazz = (*obj)->clazz;
1258
1259 if (isForward(clazz)) {
1260 // LOGI("forwarding %p @ %p to %p", *obj, obj, (void *)((uintptr_t)clazz & ~0x1));
1261 *obj = (Object *)getForward(clazz);
1262 } else if (clazz == NULL) {
1263 // LOGI("scavangeReference %p has a NULL class object", *obj);
1264 assert(!"implemented");
1265 } else if (clazz == gDvm.unlinkedJavaLangClass) {
1266 // LOGI("scavangeReference %p is an unlinked class object", *obj);
1267 assert(!"implemented");
1268 } else if (clazz == gDvm.classJavaLangClass) {
1269 ClassObject *toObj;
1270
1271 toObj = transportClassObject((ClassObject *)*obj);
1272 setForward(toObj, *obj);
1273 *obj = (Object *)toObj;
1274 } else if (IS_CLASS_FLAG_SET(clazz, CLASS_ISARRAY)) {
1275 ArrayObject *toObj;
1276
1277 toObj = transportArrayObject((ArrayObject *)*obj);
1278 setForward(toObj, *obj);
1279 *obj = (Object *)toObj;
1280 } else if (IS_CLASS_FLAG_SET(clazz, CLASS_ISREFERENCE)) {
1281 DataObject *toObj;
1282
1283 toObj = transportReferenceObject((DataObject *)*obj);
1284 setForward(toObj, *obj);
1285 *obj = (Object *)toObj;
1286 } else {
1287 DataObject *toObj;
1288
1289 toObj = transportDataObject((DataObject *)*obj);
1290 setForward(toObj, *obj);
1291 *obj = (Object *)toObj;
1292 }
1293exit:
1294 return sizeof(Object *);
1295}
1296
1297static void verifyReference(const void *obj)
1298{
1299 HeapSource *heapSource;
1300 size_t block;
1301 char space;
1302
1303 if (obj == NULL) {
1304 LOG_VERIFY("verifyReference(obj=%p)", obj);
1305 return;
1306 }
1307 heapSource = gDvm.gcHeap->heapSource;
1308 block = addressToBlock(heapSource, obj);
1309 space = heapSource->blockSpace[block];
1310 LOG_VERIFY("verifyReference(obj=%p),block=%zu,space=%d", obj, block, space);
1311 assert(!((uintptr_t)obj & 7));
1312 assert(isToSpace(obj));
1313 assert(dvmIsValidObject(obj));
1314}
1315
1316/*
1317 * Generic object scavenging.
1318 */
1319
1320static size_t scavengeObject(Object *obj)
1321{
1322 ClassObject *clazz;
1323 size_t length;
1324
1325 assert(obj != NULL);
1326 clazz = obj->clazz;
1327 assert(clazz != NULL);
1328 assert(!((uintptr_t)clazz & 0x1));
1329 assert(clazz != gDvm.unlinkedJavaLangClass);
1330 if (clazz == gDvm.classJavaLangClass) {
1331 length = scavengeClassObject((ClassObject *)obj);
1332 } else if (IS_CLASS_FLAG_SET(clazz, CLASS_ISARRAY)) {
1333 length = scavengeArrayObject((ArrayObject *)obj);
1334 } else if (IS_CLASS_FLAG_SET(clazz, CLASS_ISREFERENCE)) {
1335 length = scavengeReferenceObject((DataObject *)obj);
1336 } else {
1337 length = scavengeDataObject((DataObject *)obj);
1338 }
1339 return length;
1340}
1341
1342/*
1343 * External root scavenging routines.
1344 */
1345
1346static void scavengeHashTable(HashTable *table)
1347{
1348 HashEntry *entry;
1349 void *obj;
1350 int i;
1351
1352 if (table == NULL) {
1353 return;
1354 }
1355 dvmHashTableLock(table);
1356 for (i = 0; i < table->tableSize; ++i) {
1357 entry = &table->pEntries[i];
1358 obj = entry->data;
1359 if (obj == NULL || obj == HASH_TOMBSTONE) {
1360 continue;
1361 }
1362 scavengeReference((Object **)(void *)&entry->data);
1363 }
1364 dvmHashTableUnlock(table);
1365}
1366
1367static void pinHashTableEntries(HashTable *table)
1368{
1369 HashEntry *entry;
1370 void *obj;
1371 int i;
1372
1373 LOGI(">>> pinHashTableEntries(table=%p)", table);
1374 if (table == NULL) {
1375 return;
1376 }
1377 dvmHashTableLock(table);
1378 for (i = 0; i < table->tableSize; ++i) {
1379 entry = &table->pEntries[i];
1380 obj = entry->data;
1381 if (obj == NULL || obj == HASH_TOMBSTONE) {
1382 continue;
1383 }
1384 pinObject(entry->data);
1385 }
1386 dvmHashTableUnlock(table);
1387 LOGI("<<< pinHashTableEntries(table=%p)", table);
1388}
1389
1390static void pinPrimitiveClasses(void)
1391{
1392 size_t length;
1393 size_t i;
1394
1395 length = ARRAYSIZE(gDvm.primitiveClass);
1396 for (i = 0; i < length; i++) {
1397 if (gDvm.primitiveClass[i] != NULL) {
1398 pinObject((Object *)gDvm.primitiveClass[i]);
1399 }
1400 }
1401}
1402
1403/*
1404 * Scavenge interned strings. Permanent interned strings will have
1405 * been pinned and are therefore ignored. Non-permanent strings that
1406 * have been forwarded are snapped. All other entries are removed.
1407 */
1408static void scavengeInternedStrings(void)
1409{
1410 HashTable *table;
1411 HashEntry *entry;
1412 Object *obj;
1413 int i;
1414
1415 table = gDvm.internedStrings;
1416 if (table == NULL) {
1417 return;
1418 }
1419 dvmHashTableLock(table);
1420 for (i = 0; i < table->tableSize; ++i) {
1421 entry = &table->pEntries[i];
1422 obj = (Object *)entry->data;
1423 if (obj == NULL || obj == HASH_TOMBSTONE) {
1424 continue;
1425 } else if (!isPermanentString((StringObject *)obj)) {
1426 // LOGI("entry->data=%p", entry->data);
1427 LOG_SCAVENGE(">>> string obj=%p", entry->data);
1428 /* TODO(cshapiro): detach white string objects */
1429 scavengeReference((Object **)(void *)&entry->data);
1430 LOG_SCAVENGE("<<< string obj=%p", entry->data);
1431 }
1432 }
1433 dvmHashTableUnlock(table);
1434}
1435
1436static void pinInternedStrings(void)
1437{
1438 HashTable *table;
1439 HashEntry *entry;
1440 Object *obj;
1441 int i;
1442
1443 table = gDvm.internedStrings;
1444 if (table == NULL) {
1445 return;
1446 }
1447 dvmHashTableLock(table);
1448 for (i = 0; i < table->tableSize; ++i) {
1449 entry = &table->pEntries[i];
1450 obj = (Object *)entry->data;
1451 if (obj == NULL || obj == HASH_TOMBSTONE) {
1452 continue;
1453 } else if (isPermanentString((StringObject *)obj)) {
1454 obj = (Object *)getPermanentString((StringObject*)obj);
1455 LOG_PROMOTE(">>> pin string obj=%p", obj);
1456 pinObject(obj);
1457 LOG_PROMOTE("<<< pin string obj=%p", obj);
1458 }
1459 }
1460 dvmHashTableUnlock(table);
1461}
1462
1463static void verifyInternedStrings(void)
1464{
1465 HashTable *table;
1466 HashEntry *entry;
1467 Object *fwd, *obj;
1468 int i;
1469
1470 table = gDvm.internedStrings;
1471 if (table == NULL) {
1472 return;
1473 }
1474 dvmHashTableLock(table);
1475 for (i = 0; i < table->tableSize; ++i) {
1476 entry = &table->pEntries[i];
1477 obj = (Object *)entry->data;
1478 if (obj == NULL || obj == HASH_TOMBSTONE) {
1479 continue;
1480 } else if (isPermanentString((StringObject *)obj)) {
1481 fwd = (Object *)getForward(obj);
1482 LOG_VERIFY(">>> verify string fwd=%p obj=%p", fwd, obj);
1483 verifyReference(fwd);
1484 LOG_VERIFY(">>> verify string fwd=%p obj=%p", fwd, obj);
1485 } else {
1486 LOG_SCAVENGE(">>> verify string obj=%p %p", obj, entry->data);
1487 verifyReference(obj);
1488 LOG_SCAVENGE("<<< verify string obj=%p %p", obj, entry->data);
1489 }
1490 }
1491 dvmHashTableUnlock(table);
1492}
1493
1494/*
1495 * At present, reference tables contain references that must not be
1496 * moved by the collector. Instead of scavenging each reference in
1497 * the table we pin each referenced object.
1498 */
1499static void pinReferenceTable(ReferenceTable *table)
1500{
1501 Object **entry;
1502 int i;
1503
1504 assert(table != NULL);
1505 assert(table->table != NULL);
1506 assert(table->nextEntry != NULL);
1507 for (entry = table->table; entry < table->nextEntry; ++entry) {
1508 assert(entry != NULL);
1509 assert(!isForward(*entry));
1510 pinObject(*entry);
1511 }
1512}
1513
1514static void verifyReferenceTable(const ReferenceTable *table)
1515{
1516 Object **entry;
1517 int i;
1518
1519 LOGI(">>> verifyReferenceTable(table=%p)", table);
1520 for (entry = table->table; entry < table->nextEntry; ++entry) {
1521 assert(entry != NULL);
1522 assert(!isForward(*entry));
1523 verifyReference(*entry);
1524 }
1525 LOGI("<<< verifyReferenceTable(table=%p)", table);
1526}
1527
1528static void scavengeLargeHeapRefTable(LargeHeapRefTable *table)
1529{
1530 Object **entry;
1531
1532 for (; table != NULL; table = table->next) {
1533 for (entry = table->refs.table; entry < table->refs.nextEntry; ++entry) {
1534 if ((uintptr_t)*entry & ~0x3) {
1535 /* It's a pending reference operation. */
1536 assert(!"implemented");
1537 }
1538 scavengeReference(entry);
1539 }
1540 }
1541}
1542
1543/* This code was copied from Thread.c */
1544static void scavengeThreadStack(Thread *thread)
1545{
1546 const u4 *framePtr;
1547#if WITH_EXTRA_GC_CHECKS > 1
1548 bool first = true;
1549#endif
1550
1551 framePtr = (const u4 *)thread->curFrame;
1552 while (framePtr != NULL) {
1553 const StackSaveArea *saveArea;
1554 const Method *method;
1555
1556 saveArea = SAVEAREA_FROM_FP(framePtr);
1557 method = saveArea->method;
Carl Shapirodc1e4f12010-05-01 22:27:56 -07001558 if (method == NULL) {
1559 /* this is a break frame, nothing to do */
1560 } else if (dvmIsNativeMethod(method)) {
1561 /*
1562 * For purposes of marking references, we don't need to do
1563 * anything here, because all of the native "ins" were copied
1564 * from registers in the caller's stack frame and won't be
1565 * changed (an interpreted method can freely use registers
1566 * with parameters like any other register, but natives don't
1567 * work that way).
1568 *
1569 * However, we need to ensure that references visible to
1570 * native methods don't move around. We can do a precise scan
1571 * of the arguments by examining the method signature.
1572 */
1573 LOGI("+++ native scan %s.%s\n",
1574 method->clazz->descriptor, method->name);
1575 assert(method->registersSize == method->insSize);
1576 const char* shorty = method->shorty+1; // skip return value
1577 if (!dvmIsStaticMethod(method)) {
1578 /* grab the "this" pointer */
1579 Object* obj = (Object*) *framePtr++;
1580 if (obj == NULL) {
1581 /*
1582 * This can happen for the "fake" entry frame inserted
1583 * for threads created outside the VM. There's no actual
1584 * call so there's no object. If we changed the fake
1585 * entry method to be declared "static" then this
1586 * situation should never occur.
1587 */
1588 } else {
1589 assert(dvmIsValidObject(obj));
1590 pinObject(obj);
1591 }
1592 }
1593
1594 Object* obj;
1595 int i;
1596 for (i = method->registersSize - 1; i >= 0; i--, framePtr++) {
1597 switch (*shorty++) {
1598 case 'L':
1599 obj = (Object*) *framePtr;
1600 if (obj != NULL) {
1601 assert(dvmIsValidObject(obj));
1602 pinObject(obj);
1603 }
1604 break;
1605 case 'D':
1606 case 'J':
1607 framePtr++;
1608 break;
1609 default:
1610 /* 32-bit non-reference value */
1611 obj = (Object*) *framePtr; // debug, remove
1612 if (dvmIsValidObject(obj)) { // debug, remove
1613 /* if we see a lot of these, our scan might be off */
1614 LOGI("+++ did NOT pin obj %p\n", obj);
1615 }
1616 break;
1617 }
1618 }
1619 } else {
Carl Shapirod28668c2010-04-15 16:10:00 -07001620#ifdef COUNT_PRECISE_METHODS
1621 /* the GC is running, so no lock required */
1622 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
1623 LOGI("PGC: added %s.%s %p\n",
1624 method->clazz->descriptor, method->name, method);
1625#endif
1626#if WITH_EXTRA_GC_CHECKS > 1
1627 /*
1628 * May also want to enable the memset() in the "invokeMethod"
1629 * goto target in the portable interpreter. That sets the stack
1630 * to a pattern that makes referring to uninitialized data
1631 * very obvious.
1632 */
1633
1634 if (first) {
1635 /*
1636 * First frame, isn't native, check the "alternate" saved PC
1637 * as a sanity check.
1638 *
1639 * It seems like we could check the second frame if the first
1640 * is native, since the PCs should be the same. It turns out
1641 * this doesn't always work. The problem is that we could
1642 * have calls in the sequence:
1643 * interp method #2
1644 * native method
1645 * interp method #1
1646 *
1647 * and then GC while in the native method after returning
1648 * from interp method #2. The currentPc on the stack is
1649 * for interp method #1, but thread->currentPc2 is still
1650 * set for the last thing interp method #2 did.
1651 *
1652 * This can also happen in normal execution:
1653 * - sget-object on not-yet-loaded class
1654 * - class init updates currentPc2
1655 * - static field init is handled by parsing annotations;
1656 * static String init requires creation of a String object,
1657 * which can cause a GC
1658 *
1659 * Essentially, any pattern that involves executing
1660 * interpreted code and then causes an allocation without
1661 * executing instructions in the original method will hit
1662 * this. These are rare enough that the test still has
1663 * some value.
1664 */
1665 if (saveArea->xtra.currentPc != thread->currentPc2) {
1666 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
1667 saveArea->xtra.currentPc, thread->currentPc2,
1668 method->clazz->descriptor, method->name, method->insns);
1669 if (saveArea->xtra.currentPc != NULL)
1670 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
1671 if (thread->currentPc2 != NULL)
1672 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
1673 dvmDumpThread(thread, false);
1674 }
1675 } else {
1676 /*
1677 * It's unusual, but not impossible, for a non-first frame
1678 * to be at something other than a method invocation. For
1679 * example, if we do a new-instance on a nonexistent class,
1680 * we'll have a lot of class loader activity on the stack
1681 * above the frame with the "new" operation. Could also
1682 * happen while we initialize a Throwable when an instruction
1683 * fails.
1684 *
1685 * So there's not much we can do here to verify the PC,
1686 * except to verify that it's a GC point.
1687 */
1688 }
1689 assert(saveArea->xtra.currentPc != NULL);
1690#endif
1691
1692 const RegisterMap* pMap;
1693 const u1* regVector;
1694 int i;
1695
1696 Method* nonConstMethod = (Method*) method; // quiet gcc
1697 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
1698
1699 /* assert(pMap != NULL); */
1700
1701 //LOGI("PGC: %s.%s\n", method->clazz->descriptor, method->name);
1702
1703 if (pMap != NULL) {
1704 /* found map, get registers for this address */
1705 int addr = saveArea->xtra.currentPc - method->insns;
1706 regVector = dvmRegisterMapGetLine(pMap, addr);
1707 /*
1708 if (regVector == NULL) {
1709 LOGI("PGC: map but no entry for %s.%s addr=0x%04x\n",
1710 method->clazz->descriptor, method->name, addr);
1711 } else {
1712 LOGI("PGC: found map for %s.%s 0x%04x (t=%d)\n",
1713 method->clazz->descriptor, method->name, addr,
1714 thread->threadId);
1715 }
1716 */
1717 } else {
1718 /*
1719 * No map found. If precise GC is disabled this is
1720 * expected -- we don't create pointers to the map data even
1721 * if it's present -- but if it's enabled it means we're
1722 * unexpectedly falling back on a conservative scan, so it's
1723 * worth yelling a little.
1724 */
1725 if (gDvm.preciseGc) {
1726 LOGI("PGC: no map for %s.%s\n", method->clazz->descriptor, method->name);
1727 }
1728 regVector = NULL;
1729 }
1730
1731 /* assert(regVector != NULL); */
1732
1733 if (regVector == NULL) {
1734 /* conservative scan */
1735 for (i = method->registersSize - 1; i >= 0; i--) {
1736 u4 rval = *framePtr++;
1737 if (rval != 0 && (rval & 0x3) == 0) {
1738 abort();
1739 /* dvmMarkIfObject((Object *)rval); */
1740 }
1741 }
1742 } else {
1743 /*
1744 * Precise scan. v0 is at the lowest address on the
1745 * interpreted stack, and is the first bit in the register
1746 * vector, so we can walk through the register map and
1747 * memory in the same direction.
1748 *
1749 * A '1' bit indicates a live reference.
1750 */
1751 u2 bits = 1 << 1;
1752 for (i = method->registersSize - 1; i >= 0; i--) {
1753 /* u4 rval = *framePtr++; */
1754 u4 rval = *framePtr;
1755
1756 bits >>= 1;
1757 if (bits == 1) {
1758 /* set bit 9 so we can tell when we're empty */
1759 bits = *regVector++ | 0x0100;
1760 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
1761 }
1762
1763 if (rval != 0 && (bits & 0x01) != 0) {
1764 /*
1765 * Non-null, register marked as live reference. This
1766 * should always be a valid object.
1767 */
1768#if WITH_EXTRA_GC_CHECKS > 0
1769 if ((rval & 0x3) != 0 || !dvmIsValidObject((Object*) rval)) {
1770 /* this is very bad */
1771 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
1772 method->registersSize-1 - i, rval);
1773 } else
1774#endif
1775 {
1776
1777 // LOGI("stack reference %u@%p", *framePtr, framePtr);
1778 /* dvmMarkObjectNonNull((Object *)rval); */
1779 scavengeReference((Object **) framePtr);
1780 }
1781 } else {
1782 /*
1783 * Null or non-reference, do nothing at all.
1784 */
1785#if WITH_EXTRA_GC_CHECKS > 1
1786 if (dvmIsValidObject((Object*) rval)) {
1787 /* this is normal, but we feel chatty */
1788 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
1789 method->registersSize-1 - i, rval);
1790 }
1791#endif
1792 }
1793 ++framePtr;
1794 }
1795 dvmReleaseRegisterMapLine(pMap, regVector);
1796 }
1797 }
1798 /* else this is a break frame and there is nothing to mark, or
1799 * this is a native method and the registers are just the "ins",
1800 * copied from various registers in the caller's set.
1801 */
1802
1803#if WITH_EXTRA_GC_CHECKS > 1
1804 first = false;
1805#endif
1806
1807 /* Don't fall into an infinite loop if things get corrupted.
1808 */
1809 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
1810 saveArea->prevFrame == NULL);
1811 framePtr = saveArea->prevFrame;
1812 }
1813}
1814
1815static void scavengeThread(Thread *thread)
1816{
1817 assert(thread->status != THREAD_RUNNING ||
1818 thread->isSuspended ||
1819 thread == dvmThreadSelf());
1820
1821 // LOGI("scavengeThread(thread=%p)", thread);
1822
1823 // LOGI("Scavenging threadObj=%p", thread->threadObj);
1824 scavengeReference(&thread->threadObj);
1825
1826 // LOGI("Scavenging exception=%p", thread->exception);
1827 scavengeReference(&thread->exception);
1828
1829 scavengeThreadStack(thread);
1830}
1831
1832static void scavengeThreadList(void)
1833{
1834 Thread *thread;
1835
1836 dvmLockThreadList(dvmThreadSelf());
1837 thread = gDvm.threadList;
1838 while (thread) {
1839 scavengeThread(thread);
1840 thread = thread->next;
1841 }
1842 dvmUnlockThreadList();
1843}
1844
1845static void verifyThreadStack(const Thread *thread)
1846{
1847 const u4 *framePtr;
1848
1849 assert(thread != NULL);
1850 framePtr = (const u4 *)thread->curFrame;
1851 while (framePtr != NULL) {
1852 const StackSaveArea *saveArea;
1853 const Method *method;
1854
1855 saveArea = SAVEAREA_FROM_FP(framePtr);
1856 method = saveArea->method;
1857 if (method != NULL && !dvmIsNativeMethod(method)) {
1858 const RegisterMap* pMap;
1859 const u1* regVector;
1860 int i;
1861
1862 Method* nonConstMethod = (Method*) method; // quiet gcc
1863 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
1864
1865 /* assert(pMap != NULL); */
1866
1867 // LOGI("PGC: %s.%s\n", method->clazz->descriptor, method->name);
1868
1869 if (pMap != NULL) {
1870 /* found map, get registers for this address */
1871 int addr = saveArea->xtra.currentPc - method->insns;
1872 regVector = dvmRegisterMapGetLine(pMap, addr);
1873 if (regVector == NULL) {
1874 LOGI("PGC: map but no entry for %s.%s addr=0x%04x\n",
1875 method->clazz->descriptor, method->name, addr);
1876 } else {
1877 //LOGI("PGC: found map for %s.%s 0x%04x (t=%d)\n", method->clazz->descriptor, method->name, addr, thread->threadId);
1878 }
1879 } else {
1880 /*
1881 * No map found. If precise GC is disabled this is
1882 * expected -- we don't create pointers to the map data even
1883 * if it's present -- but if it's enabled it means we're
1884 * unexpectedly falling back on a conservative scan, so it's
1885 * worth yelling a little.
1886 */
1887 if (gDvm.preciseGc) {
1888 LOGI("PGC: no map for %s.%s\n",
1889 method->clazz->descriptor, method->name);
1890 }
1891 regVector = NULL;
1892 }
1893
1894 /* assert(regVector != NULL); */
1895
1896 if (regVector == NULL) {
1897 /* conservative scan */
1898 for (i = method->registersSize - 1; i >= 0; i--) {
1899 u4 rval = *framePtr++;
1900 if (rval != 0 && (rval & 0x3) == 0) {
1901 abort();
1902 /* dvmMarkIfObject((Object *)rval); */
1903 }
1904 }
1905 } else {
1906 /*
1907 * Precise scan. v0 is at the lowest address on the
1908 * interpreted stack, and is the first bit in the register
1909 * vector, so we can walk through the register map and
1910 * memory in the same direction.
1911 *
1912 * A '1' bit indicates a live reference.
1913 */
1914 u2 bits = 1 << 1;
1915 for (i = method->registersSize - 1; i >= 0; i--) {
1916 u4 rval = *framePtr;
1917
1918 bits >>= 1;
1919 if (bits == 1) {
1920 /* set bit 9 so we can tell when we're empty */
1921 bits = *regVector++ | 0x0100;
1922 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
1923 }
1924
1925 if (rval != 0 && (bits & 0x01) != 0) {
1926 /*
1927 * Non-null, register marked as live reference. This
1928 * should always be a valid object.
1929 */
1930 //LOGI("verify stack reference %p", (Object *)*framePtr);
1931 verifyReference((Object *)*framePtr);
1932 } else {
1933 /*
1934 * Null or non-reference, do nothing at all.
1935 */
1936 }
1937 ++framePtr;
1938 }
1939 dvmReleaseRegisterMapLine(pMap, regVector);
1940 }
1941 }
1942 /* else this is a break frame and there is nothing to mark, or
1943 * this is a native method and the registers are just the "ins",
1944 * copied from various registers in the caller's set.
1945 */
1946
1947 /* Don't fall into an infinite loop if things get corrupted.
1948 */
1949 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
1950 saveArea->prevFrame == NULL);
1951 framePtr = saveArea->prevFrame;
1952 }
1953}
1954
1955static void verifyThread(const Thread *thread)
1956{
1957 assert(thread->status != THREAD_RUNNING ||
1958 thread->isSuspended ||
1959 thread == dvmThreadSelf());
1960
1961 LOGI("verifyThread(thread=%p)", thread);
1962
1963 LOGI("verify threadObj=%p", thread->threadObj);
1964 verifyReference(thread->threadObj);
1965
1966 LOGI("verify exception=%p", thread->exception);
1967 verifyReference(thread->exception);
1968
1969 LOGI("verify thread->internalLocalRefTable");
1970 verifyReferenceTable(&thread->internalLocalRefTable);
1971
1972 LOGI("verify thread->jniLocalRefTable");
1973 verifyReferenceTable(&thread->jniLocalRefTable);
1974
1975 /* Can the check be pushed into the promote routine? */
1976 if (thread->jniMonitorRefTable.table) {
1977 LOGI("verify thread->jniMonitorRefTable");
1978 verifyReferenceTable(&thread->jniMonitorRefTable);
1979 }
1980
1981 verifyThreadStack(thread);
1982}
1983
1984static void verifyThreadList(void)
1985{
1986 Thread *thread;
1987
1988 dvmLockThreadList(dvmThreadSelf());
1989 thread = gDvm.threadList;
1990 while (thread) {
1991 verifyThread(thread);
1992 thread = thread->next;
1993 }
1994 dvmUnlockThreadList();
1995}
1996
1997static void pinThread(Thread *thread)
1998{
1999 assert(thread != NULL);
2000 assert(thread->status != THREAD_RUNNING ||
2001 thread->isSuspended ||
2002 thread == dvmThreadSelf());
2003 LOGI("pinThread(thread=%p)", thread);
2004
2005 LOGI("Pin internalLocalRefTable");
2006 pinReferenceTable(&thread->internalLocalRefTable);
2007
2008 LOGI("Pin jniLocalRefTable");
2009 pinReferenceTable(&thread->jniLocalRefTable);
2010
2011 /* Can the check be pushed into the promote routine? */
2012 if (thread->jniMonitorRefTable.table) {
2013 LOGI("Pin jniMonitorRefTable");
2014 pinReferenceTable(&thread->jniMonitorRefTable);
2015 }
2016}
2017
2018static void pinThreadList(void)
2019{
2020 Thread *thread;
2021
2022 dvmLockThreadList(dvmThreadSelf());
2023 thread = gDvm.threadList;
2024 while (thread) {
2025 pinThread(thread);
2026 thread = thread->next;
2027 }
2028 dvmUnlockThreadList();
2029}
2030
2031/*
2032 * Heap block scavenging.
2033 */
2034
2035/*
2036 * Scavenge objects in the current block. Scavenging terminates when
2037 * the pointer reaches the highest address in the block or when a run
2038 * of zero words that continues to the highest address is reached.
2039 */
2040static void scavengeBlock(HeapSource *heapSource, size_t block)
2041{
2042 u1 *cursor;
2043 u1 *end;
2044 size_t size;
2045
2046 LOG_SCAVENGE("scavengeBlock(heapSource=%p,block=%zu)", heapSource, block);
2047
2048 assert(heapSource != NULL);
2049 assert(block < heapSource->totalBlocks);
2050 assert(heapSource->blockSpace[block] == BLOCK_TO_SPACE);
2051
2052 cursor = blockToAddress(heapSource, block);
2053 end = cursor + BLOCK_SIZE;
2054 LOG_SCAVENGE("scavengeBlock start=%p, end=%p", cursor, end);
2055
2056 /* Parse and scavenge the current block. */
2057 size = 0;
2058 while (cursor < end) {
2059 u4 word = *(u4 *)cursor;
2060 if (word != 0) {
2061 size = scavengeObject((Object *)cursor);
2062 size = alignUp(size, ALLOC_ALIGNMENT);
2063 cursor += size;
2064 } else if (word == 0 && cursor == (u1 *)gDvm.unlinkedJavaLangClass) {
2065 size = sizeof(ClassObject);
2066 cursor += size;
2067 } else {
2068 /* Check for padding. */
2069 while (*(u4 *)cursor == 0) {
2070 cursor += 4;
2071 if (cursor == end) break;
2072 }
2073 /* Punt if something went wrong. */
2074 assert(cursor == end);
2075 }
2076 }
2077}
2078
2079static size_t objectSize(Object *obj)
2080{
2081 size_t size;
2082
2083 if (obj->clazz == gDvm.classJavaLangClass ||
2084 obj->clazz == gDvm.unlinkedJavaLangClass) {
2085 size = dvmClassObjectSize((ClassObject *)obj);
2086 } else if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
2087 size = dvmArrayObjectSize((ArrayObject *)obj);
2088 } else {
2089 size = obj->clazz->objectSize;
2090 }
2091 return size;
2092}
2093
2094static void verifyBlock(HeapSource *heapSource, size_t block)
2095{
2096 u1 *cursor;
2097 u1 *end;
2098 size_t size;
2099
2100 // LOGI("verifyBlock(heapSource=%p,block=%zu)", heapSource, block);
2101
2102 assert(heapSource != NULL);
2103 assert(block < heapSource->totalBlocks);
2104 assert(heapSource->blockSpace[block] == BLOCK_TO_SPACE);
2105
2106 cursor = blockToAddress(heapSource, block);
2107 end = cursor + BLOCK_SIZE;
2108 // LOGI("verifyBlock start=%p, end=%p", cursor, end);
2109
2110 /* Parse and scavenge the current block. */
2111 size = 0;
2112 while (cursor < end) {
2113 u4 word = *(u4 *)cursor;
2114 if (word != 0) {
2115 dvmVerifyObject((Object *)cursor);
2116 size = objectSize((Object *)cursor);
2117 size = alignUp(size, ALLOC_ALIGNMENT);
2118 cursor += size;
2119 } else if (word == 0 && cursor == (u1 *)gDvm.unlinkedJavaLangClass) {
2120 size = sizeof(ClassObject);
2121 cursor += size;
2122 } else {
2123 /* Check for padding. */
2124 while (*(unsigned long *)cursor == 0) {
2125 cursor += 4;
2126 if (cursor == end) break;
2127 }
2128 /* Punt if something went wrong. */
2129 assert(cursor == end);
2130 }
2131 }
2132}
2133
2134static void describeBlockQueue(const HeapSource *heapSource)
2135{
2136 size_t block, count;
2137 char space;
2138
2139 block = heapSource->queueHead;
2140 count = 0;
2141 LOG_SCAVENGE(">>> describeBlockQueue(heapSource=%p)", heapSource);
2142 /* Count the number of blocks enqueued. */
2143 while (block != QUEUE_TAIL) {
2144 block = heapSource->blockQueue[block];
2145 ++count;
2146 }
2147 LOG_SCAVENGE("blockQueue %zu elements, enqueued %zu",
2148 count, heapSource->queueSize);
2149 block = heapSource->queueHead;
2150 while (block != QUEUE_TAIL) {
2151 space = heapSource->blockSpace[block];
2152 LOG_SCAVENGE("block=%zu@%p,space=%zu", block, blockToAddress(heapSource,block), space);
2153 block = heapSource->blockQueue[block];
2154 }
2155
2156 LOG_SCAVENGE("<<< describeBlockQueue(heapSource=%p)", heapSource);
2157}
2158
2159/*
2160 * Blackens promoted objects.
2161 */
2162static void scavengeBlockQueue(void)
2163{
2164 HeapSource *heapSource;
2165 size_t block;
2166
2167 LOG_SCAVENGE(">>> scavengeBlockQueue()");
2168 heapSource = gDvm.gcHeap->heapSource;
2169 describeBlockQueue(heapSource);
2170 while (heapSource->queueHead != QUEUE_TAIL) {
2171 block = heapSource->queueHead;
2172 LOG_SCAVENGE("Dequeueing block %zu\n", block);
2173 scavengeBlock(heapSource, block);
2174 heapSource->queueHead = heapSource->blockQueue[block];
2175 LOGI("New queue head is %zu\n", heapSource->queueHead);
2176 }
2177 LOG_SCAVENGE("<<< scavengeBlockQueue()");
2178}
2179
2180/*
2181 * Scan the block list and verify all blocks that are marked as being
2182 * in new space. This should be parametrized so we can invoke this
2183 * routine outside of the context of a collection.
2184 */
2185static void verifyNewSpace(void)
2186{
2187 HeapSource *heapSource;
2188 size_t i;
2189 size_t c0, c1, c2, c7;
2190
2191 c0 = c1 = c2 = c7 = 0;
2192 heapSource = gDvm.gcHeap->heapSource;
2193 for (i = 0; i < heapSource->totalBlocks; ++i) {
2194 switch (heapSource->blockSpace[i]) {
2195 case BLOCK_FREE: ++c0; break;
2196 case BLOCK_TO_SPACE: ++c1; break;
2197 case BLOCK_FROM_SPACE: ++c2; break;
2198 case BLOCK_CONTINUED: ++c7; break;
2199 default: assert(!"reached");
2200 }
2201 }
2202 LOG_VERIFY("Block Demographics: "
2203 "Free=%zu,ToSpace=%zu,FromSpace=%zu,Continued=%zu",
2204 c0, c1, c2, c7);
2205 for (i = 0; i < heapSource->totalBlocks; ++i) {
2206 if (heapSource->blockSpace[i] != BLOCK_TO_SPACE) {
2207 continue;
2208 }
2209 verifyBlock(heapSource, i);
2210 }
2211}
2212
2213static void scavengeGlobals(void)
2214{
2215 scavengeReference((Object **)(void *)&gDvm.classJavaLangClass);
2216 scavengeReference((Object **)(void *)&gDvm.classJavaLangClassArray);
2217 scavengeReference((Object **)(void *)&gDvm.classJavaLangError);
2218 scavengeReference((Object **)(void *)&gDvm.classJavaLangObject);
2219 scavengeReference((Object **)(void *)&gDvm.classJavaLangObjectArray);
2220 scavengeReference((Object **)(void *)&gDvm.classJavaLangRuntimeException);
2221 scavengeReference((Object **)(void *)&gDvm.classJavaLangString);
2222 scavengeReference((Object **)(void *)&gDvm.classJavaLangThread);
2223 scavengeReference((Object **)(void *)&gDvm.classJavaLangVMThread);
2224 scavengeReference((Object **)(void *)&gDvm.classJavaLangThreadGroup);
2225 scavengeReference((Object **)(void *)&gDvm.classJavaLangThrowable);
2226 scavengeReference((Object **)(void *)&gDvm.classJavaLangStackTraceElement);
2227 scavengeReference((Object **)(void *)&gDvm.classJavaLangStackTraceElementArray);
2228 scavengeReference((Object **)(void *)&gDvm.classJavaLangAnnotationAnnotationArray);
2229 scavengeReference((Object **)(void *)&gDvm.classJavaLangAnnotationAnnotationArrayArray);
2230 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectAccessibleObject);
2231 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectConstructor);
2232 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectConstructorArray);
2233 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectField);
2234 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectFieldArray);
2235 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectMethod);
2236 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectMethodArray);
2237 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectProxy);
2238 scavengeReference((Object **)(void *)&gDvm.classJavaLangExceptionInInitializerError);
2239 scavengeReference((Object **)(void *)&gDvm.classJavaLangRefReference);
2240 scavengeReference((Object **)(void *)&gDvm.classJavaNioReadWriteDirectByteBuffer);
2241 scavengeReference((Object **)(void *)&gDvm.classJavaSecurityAccessController);
2242 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyLangAnnotationAnnotationFactory);
2243 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyLangAnnotationAnnotationMember);
2244 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyLangAnnotationAnnotationMemberArray);
2245 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyNioInternalDirectBuffer);
2246 scavengeReference((Object **)(void *)&gDvm.classArrayBoolean);
2247 scavengeReference((Object **)(void *)&gDvm.classArrayChar);
2248 scavengeReference((Object **)(void *)&gDvm.classArrayFloat);
2249 scavengeReference((Object **)(void *)&gDvm.classArrayDouble);
2250 scavengeReference((Object **)(void *)&gDvm.classArrayByte);
2251 scavengeReference((Object **)(void *)&gDvm.classArrayShort);
2252 scavengeReference((Object **)(void *)&gDvm.classArrayInt);
2253 scavengeReference((Object **)(void *)&gDvm.classArrayLong);
2254}
2255
2256void describeHeap(void)
2257{
2258 HeapSource *heapSource;
2259
2260 heapSource = gDvm.gcHeap->heapSource;
2261 describeBlocks(heapSource);
2262}
2263
2264/*
2265 * The collection interface. Collection has a few distinct phases.
2266 * The first is flipping AKA condemning AKA whitening the heap. The
2267 * second is to promote all objects which are pointed to by pinned or
2268 * ambiguous references. The third phase is tracing from the stacks,
2269 * registers and various globals. Lastly, a verification of the heap
2270 * is performed. The last phase should be optional.
2271 */
2272void dvmScavengeRoots(void) /* Needs a new name badly */
2273{
2274 HeapRefTable *refs;
2275 GcHeap *gcHeap;
2276
2277 {
2278 size_t alloc, unused, total;
2279
2280 room(&alloc, &unused, &total);
2281 LOGI("BEFORE GC: %zu alloc, %zu free, %zu total.",
2282 alloc, unused, total);
2283 }
2284
2285 gcHeap = gDvm.gcHeap;
2286 dvmHeapSourceFlip();
2287
2288 /*
2289 * Promote blocks with stationary objects.
2290 */
2291
2292 // LOGI("Pinning gDvm.threadList");
2293 pinThreadList();
2294
2295 // LOGI("Pinning gDvm.jniGlobalRefTable");
2296 pinReferenceTable(&gDvm.jniGlobalRefTable);
2297
2298 // LOGI("Pinning gDvm.jniPinRefTable");
2299 pinReferenceTable(&gDvm.jniPinRefTable);
2300
2301 // LOGI("Pinning gDvm.gcHeap->nonCollectableRefs");
2302 pinReferenceTable(&gcHeap->nonCollectableRefs);
2303
2304 // LOGI("Pinning gDvm.loadedClasses");
2305 pinHashTableEntries(gDvm.loadedClasses);
2306
2307 // LOGI("Pinning gDvm.primitiveClass");
2308 pinPrimitiveClasses();
2309
2310 // LOGI("Pinning gDvm.internedStrings");
2311 pinInternedStrings();
2312
2313 // describeBlocks(gcHeap->heapSource);
2314
2315 /*
2316 * Create first, open new-space page right here.
2317 */
2318
2319 /* Reset allocation to an unallocated block. */
2320 gDvm.gcHeap->heapSource->allocPtr = allocateBlocks(gDvm.gcHeap->heapSource, 1);
2321 gDvm.gcHeap->heapSource->allocLimit = gDvm.gcHeap->heapSource->allocPtr + BLOCK_SIZE;
2322 /*
2323 * Hack: promote the empty block allocated above. If the
2324 * promotions that occurred above did not actually gray any
2325 * objects, the block queue may be empty. We must force a
2326 * promotion to be safe.
2327 */
2328 promoteBlockByAddr(gDvm.gcHeap->heapSource, gDvm.gcHeap->heapSource->allocPtr);
2329
2330 /*
2331 * Scavenge blocks and relocate movable objects.
2332 */
2333
2334 LOGI("Scavenging gDvm.threadList");
2335 scavengeThreadList();
2336
2337 LOGI("Scavenging gDvm.gcHeap->referenceOperations");
2338 scavengeLargeHeapRefTable(gcHeap->referenceOperations);
2339
2340 LOGI("Scavenging gDvm.gcHeap->pendingFinalizationRefs");
2341 scavengeLargeHeapRefTable(gcHeap->pendingFinalizationRefs);
2342
2343 LOGI("Scavenging random global stuff");
2344 scavengeReference(&gDvm.outOfMemoryObj);
2345 scavengeReference(&gDvm.internalErrorObj);
2346 scavengeReference(&gDvm.noClassDefFoundErrorObj);
2347
2348 LOGI("Scavenging gDvm.dbgRegistry");
2349 scavengeHashTable(gDvm.dbgRegistry);
2350
2351 // LOGI("Scavenging gDvm.internedString");
2352 scavengeInternedStrings();
2353
2354 LOGI("Root scavenge has completed.");
2355
2356 scavengeBlockQueue();
2357
2358 LOGI("Re-snap global class pointers.");
2359 scavengeGlobals();
2360
2361 LOGI("New space scavenge has completed.");
2362
2363 /*
2364 * Verify the stack and heap.
2365 */
2366
2367 // LOGI("Validating new space.");
2368
2369 verifyInternedStrings();
2370
2371 verifyThreadList();
2372
2373 verifyNewSpace();
2374
2375 // LOGI("New space verify has completed.");
2376
2377 //describeBlocks(gcHeap->heapSource);
2378
2379 clearFromSpace(gcHeap->heapSource);
2380
2381 {
2382 size_t alloc, rem, total;
2383
2384 room(&alloc, &rem, &total);
2385 LOGI("AFTER GC: %zu alloc, %zu free, %zu total.", alloc, rem, total);
2386 }
2387}
2388
2389/*
2390 * Interface compatibility routines.
2391 */
2392
2393void dvmClearWhiteRefs(Object **list)
2394{
2395 /* TODO */
2396 assert(*list == NULL);
2397}
2398
2399void dvmHandleSoftRefs(Object **list)
2400{
2401 /* TODO */
2402 assert(*list == NULL);
2403}
2404
2405bool dvmHeapBeginMarkStep(GcMode mode)
2406{
2407 /* do nothing */
2408 return true;
2409}
2410
2411void dvmHeapFinishMarkStep(void)
2412{
2413 /* do nothing */
2414}
2415
2416void dvmHeapMarkRootSet(void)
2417{
2418 /* do nothing */
2419}
2420
2421void dvmHeapScanMarkedObjects(void)
2422{
2423 dvmScavengeRoots();
2424}
2425
2426void dvmHeapScheduleFinalizations(void)
2427{
2428 /* do nothing */
2429}
2430
2431void dvmHeapSweepUnmarkedObjects(GcMode mode, int *numFreed, size_t *sizeFreed)
2432{
2433 /* do nothing */
2434}
2435
2436void dvmMarkObjectNonNull(const Object *obj)
2437{
2438 assert(!"implemented");
2439}