-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalloc.cpp
2257 lines (1772 loc) · 73.6 KB
/
alloc.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "std.h"
#include "rope.h"
#include "alloc.h"
#include "thread.h"
#include "lock.h"
#include "symbol.h"
#include "excep.h"
#include "SpmtThread.h"
/* Trace GC heap mark/sweep phases - useful for debugging heap
* corruption */
#ifdef TRACEGC
#define TRACE_GC(fmt, ...) jam_printf(fmt, ## __VA_ARGS__)
#else
#define TRACE_GC(fmt, ...)
#endif
/* Trace GC Compaction phase */
#ifdef TRACECOMPACT
#define TRACE_COMPACT(fmt, ...) jam_printf(fmt, ## __VA_ARGS__)
#else
#define TRACE_COMPACT(fmt, ...)
#endif
/* Trace class, object and array allocation */
#ifdef TRACEALLOC
#define TRACE_ALLOC(fmt, ...) jam_printf(fmt, ## __VA_ARGS__)
#else
#define TRACE_ALLOC(fmt, ...)
#endif
/* Trace object finalization */
#ifdef TRACEFNLZ
#define TRACE_FNLZ(fmt, ...) jam_printf(fmt, ## __VA_ARGS__)
#else
#define TRACE_FNLZ(fmt, ...)
#endif
/* Object alignment */
#define OBJECT_GRAIN 8
/* Bits used within the chunk header (see also alloc.h) */
#define ALLOC_BIT 1
#define SPECIAL_BIT 4
#define HAS_HASHCODE_BIT (1<<31)
#define HASHCODE_TAKEN_BIT (1<<30)
#define HDR_FLAGS_MASK ~(ALLOC_BIT|FLC_BIT|SPECIAL_BIT| \
HAS_HASHCODE_BIT|HASHCODE_TAKEN_BIT)
/* Macros for getting values from the chunk header */
#define HEADER(ptr) *((uintptr_t*)ptr)
#define HDR_SIZE(hdr) (hdr & HDR_FLAGS_MASK)
#define HDR_ALLOCED(hdr) (hdr & ALLOC_BIT)
#define HDR_THREADED(hdr) ((hdr & (ALLOC_BIT|FLC_BIT)) == FLC_BIT)
#define HDR_SPECIAL_OBJ(hdr) (hdr & SPECIAL_BIT)
#define HDR_HASHCODE_TAKEN(hdr) (hdr & HASHCODE_TAKEN_BIT)
#define HDR_HAS_HASHCODE(hdr) (hdr & HAS_HASHCODE_BIT)
/* Macro to mark an object as "special" by setting the special
bit in the block header. These are treated differently by GC */
#define SET_SPECIAL_OB(ob) { \
uintptr_t *hdr_addr = HDR_ADDRESS(ob); \
*hdr_addr |= SPECIAL_BIT; \
}
/* 1 word header format
31 210
-------------------------------------------
| block size | |
-------------------------------------------
^ has hashcode bit ^ alloc bit
^ hashcode taken bit ^ flc bit
^ special bit
*/
static int verbosegc;
static int compact_override;
static int compact_value;
/* Format of an unallocated chunk */
typedef struct chunk {
uintptr_t header;
struct chunk *next;
} Chunk;
/* The free list head, and next allocation pointer */
static Chunk *freelist;
static Chunk **chunkpp = &freelist;
/* Heap limits */
static char *heapbase;
static char *heaplimit;
static char *heapmax;
static unsigned long heapfree;
/* The mark bit array, used for marking objects during
the mark phase. Allocated on start-up. */
static unsigned int *markBits;
static int markBitSize;
/* List holding objects which need to be finalized */
static Object **has_finaliser_list = NULL;
static int has_finaliser_count = 0;
static int has_finaliser_size = 0;
/* Compaction needs to know which object references are
conservative (i.e. looks like a reference). The objects
can't be moved in case they aren't really references. */
static Object **conservative_roots = NULL;
static int conservative_root_count = 0;
/* Above list is transformed into a hashtable before compaction */
static uintptr_t *con_roots_hashtable;
static int con_roots_hashtable_size;
/* List holding object references from outside the heap
which have been registered with the GC. Unregistered
references (outside of known structures) will not be
scanned or threaded during GC/Compaction */
static Object ***registered_refs = NULL;
static int registered_refs_count = 0;
/* The circular list holding finalized objects waiting for
their finalizer to be ran by the finalizer thread */
static Object **run_finaliser_list = NULL;
static int run_finaliser_start = 0;
static int run_finaliser_end = 0;
static int run_finaliser_size = 0;
/* The circular list holding references to be enqueued
by the reference handler thread */
static Object **reference_list = NULL;
static int reference_start = 0;
static int reference_end = 0;
static int reference_size = 0;
/* Flags set during GC if a thread needs to be woken up. The
notification is done after the world is resumed, to remove
the use of "unsafe" calls while threads are suspended. */
static int notify_reference_thread;
static int notify_finaliser_thread;
/* Internal locks protecting the GC lists and heap */
static VMLock heap_lock;
static VMLock has_fnlzr_lock;
static VMLock registered_refs_lock;
static VMWaitLock run_finaliser_lock;
static VMWaitLock reference_lock;
/* A pointer to the finalizer thread. */
static Thread *finalizer_thread;
/* Pre-allocated OutOfMemoryError */
static Object *oom;
/* Cached primitive type array classes -- used to speed up
primitive array allocation */
static Class *bool_array_class = NULL, *byte_array_class = NULL;
static Class *char_array_class = NULL, *short_array_class = NULL;
static Class *int_array_class = NULL, *float_array_class = NULL;
static Class *double_array_class = NULL, *long_array_class = NULL;
/* Field offsets and method table indexes used for finalization and
reference handling. Cached in class.c */
extern int ref_referent_offset;
extern int ref_queue_offset;
extern int finalize_mtbl_idx;
extern int enqueue_mtbl_idx;
extern int ldr_vmdata_offset;
/* During GC all threads are suspended. To safeguard against a
suspended thread holding the malloc-lock, free cannot be called
within the GC to free native memory associated with "special
objects". Instead, frees are chained together into a pending
list, and are freed once all threads are resumed. Note, we
cannot wrap malloc/realloc/free within the VM as this does
not guard against "invisible" malloc/realloc/free within libc
calls and JNI methods */
static void **pending_free_list = NULL;
void freePendingFrees();
/* Similarly, allocation for internal lists within GC cannot use
memory from the system heap. The following functions provide
the same API, but allocate memory via mmap */
void *gcMemRealloc(void *addr, int new_size);
void *gcMemMalloc(int size);
void gcMemFree(void *addr);
/* Cached system page size (used in above functions) */
static int sys_page_size;
/* The possible ways in which a reference may be marked in
the mark bit array */
#define HARD_MARK 3
#define FINALIZER_MARK 2
#define PHANTOM_MARK 1
#define LIST_INCREMENT 100
#define LOG_BYTESPERMARK LOG_OBJECT_GRAIN /* 1 mark entry for every OBJECT_GRAIN bytes of heap */
#define BITSPERMARK 2
#define LOG_BITSPERMARK 1
#define LOG_MARKSIZEBITS 5
#define MARKSIZEBITS 32
/* Macros for manipulating the mark bit array */
#define MARKENTRY(ptr) ((((char*)ptr)-heapbase)>>(LOG_BYTESPERMARK+LOG_MARKSIZEBITS-LOG_BITSPERMARK))
#define MARKOFFSET(ptr) ((((((char*)ptr)-heapbase)>>LOG_BYTESPERMARK)& \
((MARKSIZEBITS>>LOG_BITSPERMARK)-1))<<LOG_BITSPERMARK)
#define MARK(ptr,mark) markBits[MARKENTRY(ptr)]|=mark<<MARKOFFSET(ptr);
#define SET_MARK(ptr,mark) markBits[MARKENTRY(ptr)]=(markBits[MARKENTRY(ptr)]& \
~(((1<<BITSPERMARK)-1)<<MARKOFFSET(ptr)))|mark<<MARKOFFSET(ptr)
#define IS_MARKED(ptr) (int)((markBits[MARKENTRY(ptr)]>>MARKOFFSET(ptr))&((1<<BITSPERMARK)-1))
#define IS_HARD_MARKED(ptr) (IS_MARKED(ptr) == HARD_MARK)
#define IS_PHANTOM_MARKED(ptr) (IS_MARKED(ptr) == PHANTOM_MARK)
#define IS_OBJECT(ptr) (((char*)ptr) > heapbase) && \
(((char*)ptr) < heaplimit) && \
!(((uintptr_t)ptr)&(OBJECT_GRAIN-1))
#define MIN_OBJECT_SIZE ((sizeof(Object)+HEADER_SIZE+OBJECT_GRAIN-1)&~(OBJECT_GRAIN-1))
void allocMarkBits() {
int no_of_bits = (heaplimit-heapbase)>>(LOG_BYTESPERMARK-LOG_BITSPERMARK);
markBitSize = (no_of_bits+MARKSIZEBITS-1)>>LOG_MARKSIZEBITS;
markBits = (unsigned int *) sysMalloc(markBitSize*sizeof(*markBits));
TRACE_GC("Allocated mark bits - size is %d\n", markBitSize);
}
void clearMarkBits() {
memset(markBits, 0, markBitSize*sizeof(*markBits));
}
void initialiseAlloc(InitArgs *args) {
#ifdef USE_MALLOC
/* Don't use mmap - malloc max heap size */
char *mem = (char*)malloc(args->max_heap);
min = max;
if(mem == NULL) {
#else
char *mem = (char*)mmap(0, args->max_heap, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANON, -1, 0);
if(mem == MAP_FAILED) {
#endif
perror("Couldn't allocate the heap; try reducing the max heap size (-Xmx)\n");
exitVM(1);
}
/* Align heapbase so that start of heap + HEADER_SIZE is object aligned */
heapbase = (char*)(((uintptr_t)mem+HEADER_SIZE+OBJECT_GRAIN-1)&~(OBJECT_GRAIN-1))-HEADER_SIZE;
/* Ensure size of heap is multiple of OBJECT_GRAIN */
heaplimit = heapbase+((args->min_heap-(heapbase-mem))&~(OBJECT_GRAIN-1));
heapmax = heapbase+((args->max_heap-(heapbase-mem))&~(OBJECT_GRAIN-1));
/* Set initial free-list to one block covering entire heap */
freelist = (Chunk*)heapbase;
freelist->header = heapfree = heaplimit-heapbase;
freelist->next = NULL;
TRACE_GC("Alloced heap size %p\n", heaplimit-heapbase);
allocMarkBits();
/* Initialise GC locks */
initVMLock(heap_lock);
initVMLock(has_fnlzr_lock);
initVMLock(registered_refs_lock);
initVMWaitLock(run_finaliser_lock);
initVMWaitLock(reference_lock);
/* Cache system page size -- used for internal GC lists */
sys_page_size = getpagesize();
/* Set verbose option from initialisation arguments */
verbosegc = args->verbosegc;
}
/* ------------------------- MARK PHASE ------------------------- */
/* Forward declaration */
void markChildren(Object *ob, int mark, int mark_soft_refs);
int isMarked(Object *ob) {
return ob != NULL && IS_MARKED(ob);
}
void markObject(Object *object, int mark, int mark_soft_refs) {
if(object != NULL && mark > IS_MARKED(object))
markChildren(object, mark, mark_soft_refs);
}
void markRoot(Object *object) {
if(object != NULL)
MARK(object, HARD_MARK);
}
void markConservativeRoot(Object *object) {
if(object == NULL)
return;
MARK(object, HARD_MARK);
if((conservative_root_count % LIST_INCREMENT) == 0) {
int new_size = conservative_root_count + LIST_INCREMENT;
conservative_roots = (Object**)gcMemRealloc(conservative_roots,
new_size * sizeof(Object *));
}
conservative_roots[conservative_root_count++] = object;
}
void freeConservativeRoots() {
gcMemFree(conservative_roots);
conservative_roots = NULL;
conservative_root_count = 0;
}
void scan_frame(Frame* frame)
{
uintptr_t* end;
uintptr_t* slot;
slot = frame->ostack_base + frame->mb->max_stack;
end = frame->ostack_base;
if(frame->mb != NULL) {
TRACE_GC("Scanning %s.%s\n", CLASS_CB(frame->mb->classobj)->name, frame->mb->name);
TRACE_GC("lvars @%p ostack @%p\n", frame->lvars, frame->ostack);
/* Mark the method's defining class. This should always
be reachable otherwise, but mark to be safe */
markConservativeRoot((Object*)frame->mb->classobj);
}
for(; slot >= end; slot--)
if(IS_OBJECT(*slot)) {
Object *ob = (Object*)*slot;
TRACE_GC("Found Java stack ref @%p object ref is %p\n", slot, ob);
markConservativeRoot(ob);
}
}
void
Thread::scan()
{
/* TODO */ assert(false); /* TODO */
//ExecEnv *ee = thread->ee;
//Frame *frame = ee->last_frame;
//assert(ee->last_frame == thread->get_certain_core()->m_mode->frame);
Frame* frame = 0;//this->get_certain_core()->m_mode->frame;
uintptr_t *end, *slot;
TRACE_GC("Scanning stacks for thread 0x%x id %d\n", thread, this->id);
/* Mark the java.lang.Thread object */
//markConservativeRoot(ee->thread);
markConservativeRoot(this->thread);
/* Mark any pending exception raised on this thread */
//markConservativeRoot(ee->exception);
markConservativeRoot(g_get_current_thread()->exception);
/* Scan the thread's C stack and mark all references */
slot = (uintptr_t*)getStackTop(this);
end = (uintptr_t*)getStackBase(this);
for(; slot < end; slot++)
if(IS_OBJECT(*slot)) {
Object *ob = (Object*)*slot;
TRACE_GC("Found C stack ref @%p object ref is %p\n", slot, ob);
markConservativeRoot(ob);
}
/* Scan the thread's Java stack and mark all references */
// while (frame->prev != NULL) {
// scan_frame(frame);
// frame = frame->prev;
// }
scan_spmt_threads();
}
void scanThread(Thread *thread) {
thread->scan();
}
void markClassData(Class *classobj, int mark, int mark_soft_refs) {
ClassBlock *cb = CLASS_CB(classobj);
ConstantPool *cp = &cb->constant_pool;
FieldBlock *fb = cb->fields;
int i;
TRACE_GC("Marking class %s\n", cb->name);
/* Recursively mark the class's classloader */
if(cb->class_loader != NULL && mark > IS_MARKED(cb->class_loader))
markChildren(cb->class_loader, mark, mark_soft_refs);
TRACE_GC("Marking static fields for class %s\n", cb->name);
/* Static fields are initialised to default values during
preparation (done in the link phase). Therefore, don't
scan if the class hasn't been linked */
if(cb->state >= CLASS_LINKED)
for(i = 0; i < cb->fields_count; i++, fb++)
if((fb->access_flags & ACC_STATIC) &&
((*fb->type == 'L') || (*fb->type == '['))) {
Object *ob = (Object *)fb->static_value;
TRACE_GC("Field %s %s object @%p\n", fb->name, fb->type, ob);
if(ob != NULL && mark > IS_MARKED(ob))
markChildren(ob, mark, mark_soft_refs);
}
TRACE_GC("Marking constant pool resolved strings for class %s\n", cb->name);
/* Scan the constant pool and mark all resolved string references */
for(i = 1; i < cb->constant_pool_count; i++)
if(CP_TYPE(cp, i) == CONSTANT_ResolvedString) {
Object *string = (Object *)CP_INFO(cp, i);
TRACE_GC("Resolved String @ constant pool idx %d @%p\n", i, string);
if(mark > IS_MARKED(string))
markChildren(string, mark, mark_soft_refs);
}
}
void markChildren(Object *ob, int mark, int mark_soft_refs) {
Class *classobj = ob->classobj;
ClassBlock *cb = CLASS_CB(classobj);
SET_MARK(ob, mark);
if(classobj == NULL)
return;
if(mark > IS_MARKED(classobj))
markChildren((Object*)classobj, mark, mark_soft_refs);
if(cb->name[0] == '[') {
if((cb->name[1] == 'L') || (cb->name[1] == '[')) {
Object **body = (Object**)ARRAY_DATA(ob);
int len = ARRAY_LEN(ob);
int i;
TRACE_GC("Scanning Array object @%p class is %s len is %d\n", ob, cb->name, len);
for(i = 0; i < len; i++) {
Object *ob = *body++;
TRACE_GC("Object at index %d is @%p\n", i, ob);
if(ob != NULL && mark > IS_MARKED(ob))
markChildren(ob, mark, mark_soft_refs);
}
} else {
TRACE_GC("Array object @%p class is %s - Not Scanning...\n", ob, cb->name);
}
} else {
uintptr_t *body = INST_DATA(ob);
int i;
if(IS_CLASS_CLASS(cb)) {
TRACE_GC("Found class object @%p name is %s\n", ob, CLASS_CB(ob)->name);
markClassData((Class*)ob, mark, mark_soft_refs);
} else
if(IS_CLASS_LOADER(cb)) {
TRACE_GC("Mark found class loader object @%p class %s\n", ob, cb->name);
markLoaderClasses(ob, mark, mark_soft_refs);
} else
if(IS_VMTHROWABLE(cb)) {
TRACE_GC("Mark found VMThrowable object @%p\n", ob);
markVMThrowable(ob, mark, mark_soft_refs);
} else
if(IS_REFERENCE(cb)) {
Object *referent = (Object *)body[ref_referent_offset];
TRACE_GC("Mark found Reference object @%p class %s flags %d referent %p\n",
ob, cb->name, cb->flags, referent);
if(!IS_WEAK_REFERENCE(cb) && referent != NULL) {
int ref_mark = IS_MARKED(referent);
int new_mark;
if(IS_PHANTOM_REFERENCE(cb))
new_mark = PHANTOM_MARK;
else
if(!IS_SOFT_REFERENCE(cb) || mark_soft_refs)
new_mark = mark;
else
new_mark = 0;
if(new_mark > ref_mark) {
TRACE_GC("Marking referent object @%p mark %d ref_mark %d new_mark %d\n",
referent, mark, ref_mark, new_mark);
markChildren(referent, new_mark, mark_soft_refs);
}
}
}
TRACE_GC("Scanning object @%p class is %s\n", ob, cb->name);
/* The reference offsets table consists of a list of start and
end offsets corresponding to the references within the object's
instance data. Scan the list, and mark all references. */
for(i = 0; i < cb->refs_offsets_size; i++) {
int offset = cb->refs_offsets_table[i].start;
int end = cb->refs_offsets_table[i].end;
for(; offset < end; offset++) {
Object *ob = (Object *)body[offset];
TRACE_GC("Offset %d reference @%p\n", offset, ob);
if(ob != NULL && mark > IS_MARKED(ob))
markChildren(ob, mark, mark_soft_refs);
}
}
}
}
#define ADD_TO_OBJECT_LIST(list, ob) \
{ \
if(list##_start == list##_end) { \
list##_end = list##_size; \
list##_start = list##_size += LIST_INCREMENT; \
list##_list = (Object**)gcMemRealloc(list##_list, \
list##_size*sizeof(Object*)); \
} \
list##_end = list##_end%list##_size; \
list##_list[list##_end++] = ob; \
}
#define ITERATE_OBJECT_LIST(list, action) \
{ \
int i; \
\
if(list##_end > list##_start) \
for(i = list##_start; i < list##_end; i++) { \
action(list##_list[i]); \
} else { \
for(i = list##_start; i < list##_size; i++) { \
action(list##_list[i]); \
} \
for(i = 0; i < list##_end; i++) { \
action(list##_list[i]); \
} \
} \
}
static void doMark(Thread *self, int mark_soft_refs) {
char *ptr;
int i, j;
clearMarkBits();
if(oom) MARK(oom, HARD_MARK);
markBootClasses();
markJNIGlobalRefs();
scanThreads();
/* All roots should now be marked. Scan the heap and recursively
mark all marked objects - once the heap has been scanned all
reachable objects should be marked */
for(ptr = heapbase; ptr < heaplimit;) {
uintptr_t hdr = HEADER(ptr);
uintptr_t size = HDR_SIZE(hdr);
if(HDR_ALLOCED(hdr)) {
Object *ob = (Object*)(ptr+HEADER_SIZE);
if(IS_HARD_MARKED(ob))
markChildren(ob, HARD_MARK, mark_soft_refs);
}
/* Skip to next block */
ptr += size;
}
/* Now all reachable objects are marked. All other objects are garbage.
Any object with a finalizer which is unmarked, however, must have it's
finalizer ran before collecting. Scan the has_finaliser list and move
all unmarked objects to the run_finaliser list. This ensures that
finalizers are ran only once, even if finalization resurrects the
object, as objects are only added to the has_finaliser list on
creation */
for(i = 0, j = 0; i < has_finaliser_count; i++) {
Object *ob = has_finaliser_list[i];
if(!IS_HARD_MARKED(ob)) {
ADD_TO_OBJECT_LIST(run_finaliser, ob);
} else
has_finaliser_list[j++] = ob;
}
/* After scanning, j holds how many finalizers are left */
if(j != has_finaliser_count) {
has_finaliser_count = j;
/* Extra finalizers to be ran, so we need to signal the
finalizer thread in case it needs waking up. */
notify_finaliser_thread = TRUE;
}
/* Mark the objects waiting to be finalized. We must mark them
as they, and all objects they ref, cannot be deleted until the
finalizer is ran. Note, this includes objects just added,
and objects that were already on the list - they were found
to be garbage on a previous gc but we haven't got round to
finalizing them yet. */
#define RUN_MARK(element) \
markChildren(element, FINALIZER_MARK, mark_soft_refs)
ITERATE_OBJECT_LIST(run_finaliser, RUN_MARK);
/* There may be references still waiting to be enqueued by the
reference handler (from a previous GC). Remove them if
they're now unreachable as they will be collected */
#define CLEAR_UNMARKED(element) \
if(element && !IS_MARKED(element)) element = NULL
ITERATE_OBJECT_LIST(reference, CLEAR_UNMARKED);
/* Scan the interned string hash table and remove
any entries that are unmarked */
freeInternedStrings();
}
/* ------------------------- SWEEP PHASE ------------------------- */
int handleMarkedSpecial(Object *ob) {
ClassBlock *cb = CLASS_CB(ob->classobj);
int cleared = FALSE;
if(IS_REFERENCE(cb)) {
Object *referent = (Object *)INST_DATA(ob)[ref_referent_offset];
if(referent != NULL) {
int ref_mark = IS_MARKED(referent);
TRACE_GC("FREE: found Reference Object @%p class %s flags %d referent %x mark %d\n",
ob, cb->name, cb->flags, referent, ref_mark);
if(IS_PHANTOM_REFERENCE(cb)) {
if(ref_mark != PHANTOM_MARK)
goto out;
} else {
if(ref_mark == HARD_MARK)
goto out;
TRACE_GC("FREE: Clearing the referent field.\n");
INST_DATA(ob)[ref_referent_offset] = 0;
cleared = TRUE;
}
/* If the reference has a queue, add it to the list for enqueuing
by the Reference Handler thread. */
if((Object *)INST_DATA(ob)[ref_queue_offset] != NULL) {
TRACE_GC("FREE: Adding to list for enqueuing.\n");
ADD_TO_OBJECT_LIST(reference, ob);
notify_reference_thread = TRUE;
}
}
}
out:
return cleared;
}
void handleUnmarkedSpecial(Object *ob) {
if(IS_CLASS(ob)) {
if(verbosegc) {
ClassBlock *cb = CLASS_CB(ob);
if(!IS_CLASS_DUP(cb))
jam_printf("<GC: Unloading class %s>\n", cb->name);
}
freeClassData((Class*)ob);
} else
if(IS_CLASS_LOADER(CLASS_CB(ob->classobj))) {
TRACE_GC("FREE: Freeing class loader object %p\n", ob);
unloadClassLoaderDlls(ob);
freeClassLoaderData(ob);
} else
if(IS_VMTHREAD(CLASS_CB(ob->classobj))) {
/* Free the native thread structure (see comment
in detachThread (thread.c) */
TRACE_GC("FREE: Freeing native thread for VMThread object %p\n", ob);
gcPendingFree(threadSelf0(ob));
}
}
static uintptr_t doSweep(Thread *self) {
char *ptr;
Chunk newlist;
Chunk *curr = NULL, *last = &newlist;
/* Will hold the size of the largest free chunk
after scanning */
uintptr_t largest = 0;
/* Variables used to store verbose gc info */
uintptr_t marked = 0, unmarked = 0, freed = 0, cleared = 0;
/* Amount of free heap is re-calculated during scan */
heapfree = 0;
/* Scan the heap and free all unmarked objects by reconstructing
the freelist. Add all free chunks and unmarked objects and
merge adjacent free chunks into contiguous areas */
for(ptr = heapbase; ptr < heaplimit; ) {
uintptr_t hdr = HEADER(ptr);
uintptr_t size = HDR_SIZE(hdr);
Object *ob;
if(HDR_ALLOCED(hdr)) {
ob = (Object*)(ptr+HEADER_SIZE);
if(IS_MARKED(ob))
goto marked;
freed += size;
unmarked++;
if(HDR_SPECIAL_OBJ(hdr) && ob->classobj != NULL)
handleUnmarkedSpecial(ob);
TRACE_GC("FREE: Freeing ob @%p class %s - start of block\n", ob,
ob->classobj ? CLASS_CB(ob->classobj)->name : "?");
}
else
TRACE_GC("FREE: Unalloced block @%p size %d - start of block\n", ptr, size);
curr = (Chunk *) ptr;
/* Clear any set flag bits within the header */
curr->header &= HDR_FLAGS_MASK;
/* Scan the next chunks - while they are
free, merge them onto the first free
chunk */
for(;;) {
ptr += size;
if(ptr>=heaplimit)
goto out_last_free;
hdr = HEADER(ptr);
size = HDR_SIZE(hdr);
if(HDR_ALLOCED(hdr)) {
ob = (Object*)(ptr+HEADER_SIZE);
if(IS_MARKED(ob))
break;
freed += size;
unmarked++;
if(HDR_SPECIAL_OBJ(hdr) && ob->classobj != NULL)
handleUnmarkedSpecial(ob);
TRACE_GC("FREE: Freeing object @%p class %s - merging onto block @%p\n",
ob, ob->classobj ? CLASS_CB(ob->classobj)->name : "?", curr);
}
else
TRACE_GC("FREE: unalloced block @%p size %d - merging onto block @%p\n", ptr, size, curr);
curr->header += size;
}
/* Scanned to next marked object see
if it's the largest so far */
if(curr->header > largest)
largest = curr->header;
/* Add onto total count of free chunks */
heapfree += curr->header;
/* Add chunk onto the freelist only if it's
large enough to hold an object */
if(curr->header >= MIN_OBJECT_SIZE) {
last->next = curr;
last = curr;
}
marked:
marked++;
if(HDR_SPECIAL_OBJ(hdr) && ob->classobj != NULL && handleMarkedSpecial(ob))
cleared++;
/* Skip to next block */
ptr += size;
if(ptr >= heaplimit)
goto out_last_marked;
}
out_last_free:
/* Last chunk is free - need to check if
largest */
if(curr->header > largest)
largest = curr->header;
heapfree += curr->header;
/* Add chunk onto the freelist only if it's
large enough to hold an object */
if(curr->header >= MIN_OBJECT_SIZE) {
last->next = curr;
last = curr;
}
out_last_marked:
/* We've now reconstructed the freelist, set freelist
pointer to new list */
last->next = NULL;
freelist = newlist.next;
/* Reset next allocation block to beginning of list -
this leads to a search - use largest instead? */
chunkpp = &freelist;
if(verbosegc) {
long long size = heaplimit-heapbase;
long long pcnt_used = ((long long)heapfree)*100/size;
jam_printf("<GC: Allocated objects: %lld>\n", (long long)marked);
jam_printf("<GC: Freed %lld object(s) using %lld bytes",
(long long)unmarked, (long long)freed);
if(cleared)
jam_printf(", cleared %lld reference(s)", (long long)cleared);
jam_printf(">\n<GC: Largest block is %lld total free is %lld out of %lld (%lld%%)>\n",
(long long)largest, (long long)heapfree, size, pcnt_used);
}
/* Return the size of the largest free chunk in heap - this
is the largest allocation request that can be satisfied */
return largest;
}
/* ------------------------- COMPACT PHASE ------------------------- */
void threadReference(Object **ref) {
Object *ob = *ref;
uintptr_t *hdr = HDR_ADDRESS(ob);
TRACE_COMPACT("Threading ref addr %p object ref %p link %p\n", ref, ob, *hdr);
*ref = (Object*)*hdr;
*hdr = ((uintptr_t)ref | FLC_BIT);
}
void unthreadHeader(uintptr_t *hdr_addr, Object *new_addr) {
uintptr_t hdr = *hdr_addr;
TRACE_COMPACT("Unthreading header address %p new addr %p\n", hdr_addr, new_addr);
while(HDR_THREADED(hdr)) {
uintptr_t *ref_addr = (uintptr_t*)(hdr & ~0x3);
TRACE_COMPACT("updating ref address %p\n", ref_addr);
hdr = *ref_addr;
*ref_addr = (uintptr_t)new_addr;
}
TRACE_COMPACT("Replacing original header contents %p\n", hdr);
*hdr_addr = hdr;
}
static void threadObjectLists() {
int i;
for(i = 0; i < has_finaliser_count; i++)
threadReference(&has_finaliser_list[i]);
#define THREAD_REFS(element) \
if(element) threadReference(&element)
ITERATE_OBJECT_LIST(run_finaliser, THREAD_REFS);
ITERATE_OBJECT_LIST(reference, THREAD_REFS);
}
void addConservativeRoots2Hash() {
int i;
for(i = 1; i < conservative_root_count; i <<= 1);
con_roots_hashtable_size = i << 1;
con_roots_hashtable = (uintptr_t*)gcMemMalloc(con_roots_hashtable_size * sizeof(uintptr_t));
memset(con_roots_hashtable, 0, con_roots_hashtable_size * sizeof(uintptr_t));
for(i = 0; i < conservative_root_count; i++) {
uintptr_t data = ((uintptr_t)conservative_roots[i]) >> LOG_BYTESPERMARK;
int index = data & (con_roots_hashtable_size-1);
TRACE_COMPACT("Adding conservative root %p\n", conservative_roots[i]);
while(con_roots_hashtable[index] && con_roots_hashtable[index] != data)
index = (index + 1) & (con_roots_hashtable_size-1);
con_roots_hashtable[index] = data;
}
}
void registerStaticObjectRefLocked(Object **ref) {
Thread *self = threadSelf();
disableSuspend(self);
lockVMLock(registered_refs_lock, self);
registerStaticObjectRef(ref);
unlockVMLock(registered_refs_lock, self);
enableSuspend(self);
}
void registerStaticObjectRefLocked(Class** ref)
{
registerStaticObjectRefLocked((Object**)ref);
}
void registerStaticObjectRef(Object **ref) {
if((registered_refs_count % LIST_INCREMENT) == 0) {
int new_size = registered_refs_count + LIST_INCREMENT;
registered_refs = (Object***)sysRealloc(registered_refs,
new_size * sizeof(Object **));
}
registered_refs[registered_refs_count++] = ref;
}
void registerStaticObjectRef(Class** ref)
{
registerStaticObjectRef((Object**)ref);
}
void threadRegisteredReferences() {
int i;
for(i = 0; i < registered_refs_count; i++)
if(*registered_refs[i] != NULL)
threadReference(registered_refs[i]);
}
#define IS_CONSERVATIVE_ROOT(ob) \
({ \
uintptr_t data = ((uintptr_t)ob) >> LOG_BYTESPERMARK; \
int index = data & (con_roots_hashtable_size-1); \
\
while(con_roots_hashtable[index] && con_roots_hashtable[index] != data) \
index = (index + 1) & (con_roots_hashtable_size-1); \
con_roots_hashtable[index]; \
})
#define ADD_CHUNK_TO_FREELIST(start, end) \
{ \
Chunk *curr = (Chunk *) start; \
curr->header = end - start; \
\
if(curr->header >= MIN_OBJECT_SIZE) { \
last->next = curr; \
last = curr; \
} \
\
if(curr->header > largest) \
largest = curr->header; \
\
/* Add onto total count of free chunks */ \
heapfree += curr->header; \
}
int compactSlideBlock(char *block_addr, char *new_addr) {
uintptr_t hdr = HEADER(block_addr);
uintptr_t size = HDR_SIZE(hdr);
/* Slide the object down the heap. Use memcpy if
the areas don't overlap as it should be faster */
if(new_addr + size <= block_addr)
memcpy(new_addr, block_addr, size);
else
memmove(new_addr, block_addr, size);
/* If the objects hashCode (address) has been taken we must
maintain the same value after the object has been moved */
if(HDR_HASHCODE_TAKEN(hdr)) {
uintptr_t *hdr_addr = &HEADER(new_addr);
uintptr_t *hash_addr = (uintptr_t*)(new_addr + size);