-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmemory.c
1640 lines (1532 loc) · 54.6 KB
/
memory.c
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 <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include "common.h"
#include "memory.h"
#include "debug.h"
#include "vm.h"
#include "compiler.h"
#include "value.h"
#include "options.h"
#ifdef NDEBUG
#define GC_TRACE_MARK(lvl, obj) (void)0
#define GC_TRACE_FREE(lvl, obj) (void)0
#define GC_TRACE_DEBUG(lvl, ...) (void)0
#define TRACE_GC_FUNC_START(lvl, func) (void)0
#define TRACE_GC_FUNC_END(lvl, func) (void)0
#else
#define GC_TRACE_MARK(lvl, obj) gc_trace_mark(lvl, obj)
#define GC_TRACE_FREE(lvl, obj) gc_trace_free(lvl, obj)
#define GC_TRACE_DEBUG(lvl, ...) gc_trace_debug(lvl, __VA_ARGS__)
#define TRACE_GC_FUNC_START(lvl, func) trace_gc_func_start(lvl, func);
#define TRACE_GC_FUNC_END(lvl, func) trace_gc_func_end(lvl, func);
#endif
#define HEAPLIST_INCREMENT 10
#define FREE_MIN 500
#define HEAP_SLOTS 10000
static ObjAny **heapList;
static int heapListSize = 0;
static ObjAny *freeList;
static int heapsUsed = 0;
static bool inGC = false;
static bool GCOn = true;
static bool dontGC = false;
bool inYoungGC = false;
bool inFullGC = false;
bool inFinalFree = false;
bool isInGC(void) {
return inGC;
}
// debugging
static ObjType lastNewObjectRequestType = OBJ_T_NONE;
static ObjType curNewObjectRequestType = OBJ_T_NONE;
struct sGCProfile GCProf = {
.totalGCYoungTime = {
.tv_sec = 0,
.tv_usec = 0,
},
.totalGCFullTime = {
.tv_sec = 0,
.tv_usec = 0,
},
.runsYoung = 0,
.runsFull = 0,
};
static void startGCRunProfileTimer(struct timeval *timeStart) {
gettimeofday(timeStart, NULL);
}
static void stopGCRunProfileTimer(struct timeval *timeStart, struct timeval *tout) {
struct timeval timeEnd;
gettimeofday(&timeEnd, NULL);
struct timeval tdiff = { .tv_sec = 0, .tv_usec = 0 };
timersub(&timeEnd, timeStart, &tdiff);
struct timeval tres;
timeradd(tout, &tdiff, &tres);
*tout = tres; // copy
}
struct sGCStats GCStats;
int activeFinalizers = 0;
static void printGenerationInfo() {
fprintf(stderr, "Generation info:\n");
for (int i = 0; i <= GC_GEN_MAX; i++) {
fprintf(stderr, "Gen %d: %lu\n", i, GCStats.generations[i]);
}
}
static void printObjTypeSizes() {
int type = OBJ_T_NONE+1;
while (type < OBJ_T_LAST) {
fprintf(stderr, "%s size: %ld\n", objTypeName(type), sizeofObjType(type));
type++;
}
}
static void printGCDemographics() {
for (int i = OBJ_T_NONE+1; i < OBJ_T_LAST; i++) {
fprintf(stderr, "# %s: %ld\n", objTypeName(i), GCStats.demographics[i]);
}
}
static void printGCStats() {
fprintf(stderr, "GC Stats\n");
if (GET_OPTION(traceGCLvl > 2)) {
printObjTypeSizes();
}
fprintf(stderr, "ObjAny size: %ld b\n", sizeof(ObjAny));
fprintf(stderr, "heap page size: %ld KB\n", (HEAP_SLOTS*sizeof(ObjAny))/1024);
fprintf(stderr, "# heaps used: %d\n", heapsUsed);
fprintf(stderr, "Total allocated: %ld KB\n", GCStats.totalAllocated/1024);
fprintf(stderr, "Heap size: %ld KB\n", GCStats.heapSize/1024);
fprintf(stderr, "Heap used: %ld KB\n", GCStats.heapUsed/1024);
fprintf(stderr, "Heap used waste: %ld KB\n", GCStats.heapUsedWaste/1024);
fprintf(stderr, "# objects: %ld\n", GCStats.heapUsed/sizeof(ObjAny));
if (GET_OPTION(traceGCLvl > 2)) {
printGCDemographics();
}
}
void printGCProfile() {
#if GEN_GC
fprintf(stderr, "Runs Young: %lu\n", GCProf.runsYoung);
#endif
fprintf(stderr, "Runs Full: %lu\n", GCProf.runsFull);
#if GEN_GC
fprintf(stderr, "Total runs: %lu\n", GCProf.runsYoung+GCProf.runsFull);
#endif
time_t secs = 0;
suseconds_t msecs = 0;
suseconds_t millis = 0;
#if GEN_GC
secs = GCProf.totalGCYoungTime.tv_sec;
msecs = GCProf.totalGCYoungTime.tv_usec;
millis = (msecs / 1000);
while (millis > 1000) {
secs += 1;
millis = millis / 1000;
}
fprintf(stderr, "Young GC time: %ld secs, %ld ms\n",
secs, (long)millis);
#endif
secs = GCProf.totalGCFullTime.tv_sec;
msecs = GCProf.totalGCFullTime.tv_usec;
millis = (msecs / 1000);
while (millis > 1000) {
secs += 1;
millis = millis / 1000;
}
fprintf(stderr, "Full GC time: %ld secs, %ld ms\n",
secs, (long)millis);
}
void GCPromote(Obj *obj, unsigned short gen) {
if (gen > GC_GEN_MAX) gen = GC_GEN_MAX;
unsigned short oldGen = obj->GCGen;
if (GCStats.generations[oldGen])
GCStats.generations[oldGen]--;
GCStats.generations[gen]++;
obj->GCGen = gen;
}
void GCPromoteOnce(Obj *obj) {
if (obj->GCGen == GC_GEN_MAX) {
return;
}
unsigned short oldGen = obj->GCGen;
unsigned short newGen = oldGen+1;
if (GCStats.generations[oldGen])
GCStats.generations[oldGen]--;
GCStats.generations[newGen]++;
obj->GCGen = newGen;
}
static void gc_trace_mark(int lvl, Obj *obj) {
if (GET_OPTION(traceGCLvl) < lvl) return;
fprintf(stderr, "[GC]: marking %s object at %p (gen %d)", typeOfObj(obj), obj, obj->GCGen);
if (obj->type != OBJ_T_UPVALUE && obj->type != OBJ_T_INTERNAL && obj->type != OBJ_T_SCOPE) {
fprintf(stderr, ", value => ");
printValue(stderr, OBJ_VAL(obj), false, -1); // can allocate objects, must be `inGC`
}
fprintf(stderr, "\n");
}
static void gc_trace_free(int lvl, Obj *obj) {
if (GET_OPTION(traceGCLvl) < lvl) return;
fprintf(stderr, "[GC]: freeing object at %p (gen %d), ", obj, obj->GCGen);
if (obj->type == OBJ_T_UPVALUE) {
fprintf(stderr, "type => upvalue");
} else {
fprintf(stderr, "type => %s, value => ", typeOfObj(obj));
/*printValue(stderr, OBJ_VAL(obj), false, -1); // can allocate objects, must be `inGC`*/
if (obj->type == OBJ_T_INSTANCE) {
const char *className = "(anon)";
if (CLASSINFO(((ObjInstance*) obj)->klass)->name) {
className = CLASSINFO(((ObjInstance*) obj)->klass)->name->chars;
}
fprintf(stderr, ", class => %s", className);
}
}
fprintf(stderr, "\n");
}
static void gc_trace_debug(int lvl, const char *fmt, ...) {
if (GET_OPTION(traceGCLvl) < lvl) return;
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "[GC]: ");
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
static inline void trace_gc_func_start(int lvl, const char *funcName) {
if (GET_OPTION(traceGCLvl) < lvl) return;
fprintf(stderr, "[GC]: <%s>\n", funcName);
}
static inline void trace_gc_func_end(int lvl, const char *funcName) {
if (GET_OPTION(traceGCLvl) < lvl) return;
fprintf(stderr, "[GC]: </%s>\n", funcName);
}
// Generational GC details
#define YOUNG_MARK_STACK_MAX 5000
static Obj *youngStack[YOUNG_MARK_STACK_MAX];
static int youngStackSz = 0;
// remembering young objects that should not be collected until next major GC
// (they are pointed to by old objects)
static vec_void_t rememberSet;
void pushRememberSet(Obj *obj) {
static bool rememberSetInited = false;
if (UNLIKELY(!rememberSetInited)) {
vec_init(&rememberSet);
rememberSetInited = true;
}
vec_push(&rememberSet, obj);
}
void addHeap() {
ObjAny *p, *pend;
if (heapsUsed == heapListSize) {
/* Realloc heaps */
heapListSize += HEAPLIST_INCREMENT;
size_t newHeapListSz = heapListSize*sizeof(ObjAny*);
heapList = (heapsUsed > 0) ?
(ObjAny**)realloc(heapList, newHeapListSz) :
(ObjAny**)malloc(newHeapListSz);
if (heapList == 0) {
fprintf(stderr, "can't alloc new heap list\n");
_exit(1);
}
GCStats.totalAllocated += (HEAPLIST_INCREMENT*sizeof(ObjAny*));
}
size_t heapSz = sizeof(ObjAny)*HEAP_SLOTS;
p = heapList[heapsUsed++] = (ObjAny*)malloc(heapSz);
if (p == 0) {
fprintf(stderr, "addHeap: can't alloc new heap\n");
_exit(1);
}
GCStats.totalAllocated += heapSz;
GCStats.heapSize += heapSz;
pend = p + HEAP_SLOTS;
while (p < pend) { // zero out new objects
Obj *obj = (Obj*)p;
obj->type = OBJ_T_NONE;
obj->nextFree = freeList;
freeList = (ObjAny*)obj;
p++;
} // freeList points to last free entry in list, linked backwards
}
// TODO: we shouldn't free all heaps right away, we should leave one
// empty heap and mark it as empty, then we don't need to iterate over
// it during GC, and we return it on next call to addHeap().
/*static void freeHeap(ObjAny *heap) {*/
/*int i = 0;*/
/*ObjAny *curHeap = NULL;*/
/*int heapIdx = -1;*/
/*for (i = 0; i < heapsUsed; i++) {*/
/*curHeap = heapList[i];*/
/*if (curHeap && curHeap == heap) {*/
/*heapIdx = i;*/
/*}*/
/*}*/
/*ASSERT(heapIdx != -1);*/
/*memmove(heapList+heapIdx, heapList+heapIdx+1, heapListSize-heapIdx-1);*/
/*xfree(heap);*/
/*heapsUsed--;*/
/*GCStats.totalAllocated -= (sizeof(ObjAny)*HEAP_SLOTS);*/
/*GCStats.heapSize -= (sizeof(ObjAny)*HEAP_SLOTS);*/
/*}*/
static inline void pushYoungObject(Obj *obj) {
DBG_ASSERT(youngStackSz < YOUNG_MARK_STACK_MAX);
youngStack[youngStackSz++] = obj;
}
static inline bool inRememberSet(Obj *obj) {
int found = -1;
vec_find(&rememberSet, obj, found);
return found != -1;
}
// collect all young objects that aren't in the remember set, aren't
// on the stack (VM and "C" obj stack)
void collectYoungGarbage() {
ASSERT(vm.grayCount == 0);
if (!GCOn || OPTION_T(disableGC)) {
GC_TRACE_DEBUG(1, "GC run (young) skipped (GC OFF)");
return;
}
if (UNLIKELY(inGC)) {
fprintf(stderr, "[BUG]: GC (young) tried to start during a GC run?\n");
ASSERT(0);
}
if (UNLIKELY(youngStackSz == 0)) {
GC_TRACE_DEBUG(1, "Skipping garbage collect (young, stack size: %d)", youngStackSz);
return;
}
inGC = true;
inYoungGC = true;
struct timeval tRunStart;
startGCRunProfileTimer(&tRunStart);
GC_TRACE_DEBUG(1, "Collecting garbage (young, stack size: %d)", youngStackSz);
GC_TRACE_DEBUG(2, "Marking VM stack roots");
// Mark stack roots up the stack for every execution context in every thread
Obj *thObj; int thIdx = 0;
SigHandler *sigh = sigHandlers;
while (sigh) {
ASSERT(sigh->callable);
grayObject(sigh->callable);
sigh = sigh->next;
}
vec_foreach(&vm.threads, thObj, thIdx) {
DBG_ASSERT(thObj);
grayObject(thObj);
LxThread *th = THREAD_GETHIDDEN(OBJ_VAL(thObj));
ASSERT(th);
if (th->status == THREAD_ZOMBIE) {
continue;
}
if (th->lastValue) {
grayValue(*th->lastValue);
}
if (th->tlsMap) {
grayObject(TO_OBJ(th->tlsMap));
}
if (th->thisObj) {
grayObject(th->thisObj);
}
grayValue(th->lastErrorThrown);
VMExecContext *ctx = NULL; int k = 0;
vec_foreach(&th->v_ecs, ctx, k) {
grayTable(&ctx->roGlobals);
// Thread stack
for (Value *slot = ctx->stack; slot < ctx->stackTop; slot++) {
grayValue(*slot);
}
}
BlockStackEntry *bentry = NULL; int bidx = 0;
vec_foreach(&th->v_blockStack, bentry, bidx) {
grayObject((Obj*)bentry->callable);
grayObject((Obj*)bentry->cachedBlockClosure);
grayObject((Obj*)bentry->blockInstance);
}
}
GC_TRACE_DEBUG(2, "Marking per-thread VM C-call stack objects");
int numStackObjects = 0;
ObjInstance *threadInst = NULL; int tIdx = 0;
vec_foreach(&vm.threads, threadInst, tIdx) {
LxThread *curThread = THREAD_GETHIDDEN(OBJ_VAL(threadInst));
if (curThread->status == THREAD_ZOMBIE) { continue; }
Obj *stackObjPtr = NULL; int stIdx = 0;
vec_foreach(&curThread->stackObjects, stackObjPtr, stIdx) {
numStackObjects++;
grayObject(stackObjPtr);
}
}
GC_TRACE_DEBUG(2, "# C-call stack objects found: %d", numStackObjects);
grayTable(&vm.globals);
grayTable(&vm.constants);
/*grayTable(&vm.strings);*/
/*grayTable(&vm.regexLiterals);*/
Value *scriptName; int i = 0;
vec_foreach_ptr(&vm.loadedScripts, scriptName, i) {
grayValue(*scriptName);
}
GC_TRACE_DEBUG(2, "Marking VM frame functions");
// gray active function closure objects
/*int numOpenUpsFound = 0;*/
VMExecContext *ctx = NULL; int ctxIdx = 0;
thObj = NULL; thIdx = 0;
vec_foreach(&vm.threads, thObj, thIdx) {
LxThread *th = THREAD_GETHIDDEN(OBJ_VAL(thObj));
if (th->status == THREAD_ZOMBIE) continue;
vec_foreach(&th->v_ecs, ctx, ctxIdx) {
grayObject((Obj*)ctx->filename);
if (ctx->lastValue) {
grayValue(*ctx->lastValue);
}
for (unsigned i = 0; i < ctx->frameCount; i++) {
CallFrame *frame = &ctx->frames[i];
// TODO: gray native function if exists
// XXX: is this necessary, they must be on the stack??
if (frame->closure)
grayObject(TO_OBJ(frame->closure));
if (frame->instance)
grayObject(TO_OBJ(frame->instance));
if (frame->scope) {
grayObject(TO_OBJ(frame->scope));
}
}
}
if (th->openUpvalues) {
ObjUpvalue *up = th->openUpvalues;
while (up) {
ASSERT(up->value);
grayValue(*up->value);
up = up->next;
}
}
}
if (vm.printBuf) {
GC_TRACE_DEBUG(3, "Marking VM print buf");
grayObject((Obj*)vm.printBuf);
}
int numPromotedDark = 0;
int numPromotedOther = 0;
int numPromotedRemembered = 0;
int numCollected = 0;
ObjAny *newFreeList = freeList;
int grayCount = vm.grayCount;
while (grayCount > 0) {
// Pop an item from the gray stack.
grayCount--;
Obj *marked = vm.grayStack[grayCount];
DBG_ASSERT(marked);
int oldCount = vm.grayCount;
if (IS_YOUNG_OBJ(marked)) {
blackenObject(marked); // NOTE: only grays young references
}
int newCount = vm.grayCount;
grayCount += (newCount-oldCount);
}
int numNotYoung = 0;
int numHidden = 0;
for (int i = 0; i < youngStackSz; i++) {
Obj *youngObj = youngStack[i];
DBG_ASSERT(youngObj);
if (youngObj->GCGen > GC_GEN_MIN || OBJ_IS_HIDDEN(youngObj)) {
if (OBJ_IS_HIDDEN(youngObj)) {
numHidden++;
// sometimes objects are created with NEWOBJ_FLAG_NONE and then
// `GC_PROMOTE`d in the code sometime later (usually right after creation).
} else if (youngObj->GCGen > GC_GEN_MIN) {
/*fprintf(stderr, "typeof obj: %s\n", typeOfObj(youngObj));*/
/*if (OBJ_IS_INSTANCE_LIKE(youngObj)) {*/
/*fprintf(stderr, "class: %s\n", CLASSINFO(TO_INSTANCE(youngObj)->klass)->name->chars);*/
/*}*/
numNotYoung++;
}
OBJ_UNSET_DARK(youngObj);
continue;
}
// Let full GC deal with finalizer object destruction
if (activeFinalizers > 0 && youngObj->type == OBJ_T_INSTANCE &&
((ObjInstance*)youngObj)->finalizerFunc != NULL) {
numPromotedOther++;
GC_PROMOTE_ONCE(youngObj);
OBJ_UNSET_DARK(youngObj);
continue;
}
if (OBJ_IS_DARK(youngObj)) {
numPromotedDark++;
GC_PROMOTE_ONCE(youngObj);
OBJ_UNSET_DARK(youngObj);
} else if (inRememberSet(youngObj)) {
numPromotedRemembered++;
GC_PROMOTE_ONCE(youngObj);
OBJ_UNSET_DARK(youngObj);
} else {
ASSERT(IS_YOUNG_OBJ(youngObj));
ASSERT(!OBJ_IS_HIDDEN(youngObj));
youngObj->nextFree = newFreeList;
freeObject(youngObj);
newFreeList = (ObjAny*)youngObj;
numCollected++;
}
}
freeList = newFreeList;
GC_TRACE_DEBUG(2, "Ungraying grayed objects: %d", vm.grayCount);
// We whiten the objects again in case full GC runs next, which expects
// all objects to be white.
while (vm.grayCount > 0) {
// Pop an item from the gray stack.
Obj *marked = vm.grayStack[--vm.grayCount];
DBG_ASSERT(marked);
OBJ_UNSET_DARK(marked);
}
GC_TRACE_DEBUG(2, "done FREE (young) process (%d young)", youngStackSz);
GC_TRACE_DEBUG(2, "Num not young: %d", numNotYoung);
GC_TRACE_DEBUG(2, "Num promoted (hidden): %d", numHidden);
GC_TRACE_DEBUG(2, "Num promoted (dark): %d", numPromotedDark);
GC_TRACE_DEBUG(2, "Num promoted (remembered): %d", numPromotedRemembered);
GC_TRACE_DEBUG(2, "Num promoted (finalizers): %d", numPromotedOther);
GC_TRACE_DEBUG(2, "Num collected: %d", numCollected);
vec_clear(&rememberSet);
stopGCRunProfileTimer(&tRunStart, &GCProf.totalGCYoungTime);
GCProf.runsYoung++;
inYoungGC = false;
inGC = false;
vm.grayCount = 0;
youngStackSz = 0;
}
Obj *getNewObject(ObjType type, size_t sz, int flags) {
Obj *obj = NULL;
lastNewObjectRequestType = curNewObjectRequestType;
curNewObjectRequestType = type;
bool isOld = (flags & NEWOBJ_FLAG_OLD) != 0;
#if GEN_GC
bool triedYoungCollect = false;
#else
bool triedYoungCollect = true;
(void)isOld;
#endif
bool noGC = dontGC || OPTION_T(disableGC) || !GCOn;
if (noGC) triedYoungCollect = true;
int tries = 0;
#ifndef NDEBUG
#if GEN_GC
if (OPTION_T(stressGCYoung) || OPTION_T(stressGCBoth)) collectYoungGarbage();
#endif
if (OPTION_T(stressGCFull) || OPTION_T(stressGCBoth)) collectGarbage();
#endif
retry:
DBG_ASSERT(tries < 3);
#if GEN_GC
if (freeList && (isOld || ((youngStackSz < YOUNG_MARK_STACK_MAX) || triedYoungCollect))) {
#else
if (freeList) {
#endif
obj = (Obj*)freeList;
freeList = obj->nextFree;
GCStats.heapUsed += sizeof(ObjAny);
GCStats.heapUsedWaste += (sizeof(ObjAny)-sz);
GCStats.demographics[type]++;
#if GEN_GC
if (!isOld && youngStackSz < YOUNG_MARK_STACK_MAX) {
pushYoungObject(obj);
}
#endif
return obj;
}
// ran out of freelist space, try to GC or add another heap, then retry
if (!triedYoungCollect && !noGC) {
collectYoungGarbage();
triedYoungCollect = true;
} else if (noGC) {
addHeap();
} else {
collectGarbage(); // adds heap if needed at end of collection, full mark/sweep
noGC = true;
}
tries++;
goto retry;
}
// Main memory management function used by both ALLOCATE/FREE (see memory.h)
// NOTE: memory is NOT initialized to 0 (see man 3 realloc)
void *reallocate(void *previous, size_t oldSize, size_t newSize) {
TRACE_GC_FUNC_START(10, "reallocate");
if (LIKELY(vm.inited && vm.curThread)) {
ASSERT(GVLOwner == vm.curThread->tid);
}
if (UNLIKELY(newSize > 0 && inGC)) {
ASSERT(0); // if we're in GC phase we shouldn't allocate memory (other than adding heaps, if necessary)
}
if (newSize > oldSize) {
GCStats.totalAllocated += (newSize - oldSize);
GC_TRACE_DEBUG(12, "reallocate added %lu bytes", newSize-oldSize);
GC_TRACE_DEBUG(13, "totalAllocated: %lu bytes", GCStats.totalAllocated);
} else {
GCStats.totalAllocated -= (oldSize - newSize);
GC_TRACE_DEBUG(12, "reallocate freed %lu bytes", oldSize-newSize);
GC_TRACE_DEBUG(13, "totalAllocated: %lu bytes", GCStats.totalAllocated);
}
if (newSize == 0) { // freeing
GC_TRACE_DEBUG(10, " freeing %p from realloc", previous);
xfree(previous);
TRACE_GC_FUNC_END(10, "reallocate");
return NULL;
}
void *ret = realloc(previous, newSize);
if (UNLIKELY(!ret)) {
GC_TRACE_DEBUG(1, "REALLOC FAILED, trying GC");
collectGarbage(); // NOTE: GCOn could be false here if set by user
// try again after potentially freeing memory
ret = realloc(previous, newSize);
if (UNLIKELY(!ret)) {
fprintf(stderr, "Out of memory!\n");
_exit(1);
}
}
if (newSize > 0) {
GC_TRACE_DEBUG(10, " allocated %p", ret);
}
TRACE_GC_FUNC_END(10, "reallocate");
return ret;
}
void nil_mem(Value *mem, size_t num) {
Value nil = NIL_VAL;
for (size_t i = 0; i < num; i++) {
memcpy(mem+i, &nil, sizeof(Value));
}
}
static inline void INC_GEN(Obj *obj) {
if (obj->GCGen < GC_GEN_MAX) {
obj->GCGen++;
if (GCStats.generations[obj->GCGen-1])
GCStats.generations[obj->GCGen-1]--;
GCStats.generations[obj->GCGen]++;
}
}
void grayObject(Obj *obj) {
TRACE_GC_FUNC_START(4, "grayObject");
if (obj == NULL) {
TRACE_GC_FUNC_END(4, "grayObject (null obj found)");
return;
}
if (OBJ_IS_DARK(obj)) {
TRACE_GC_FUNC_END(4, "grayObject (already dark)");
return;
}
if (inYoungGC && IS_OLD_OBJ(obj)) {
TRACE_GC_FUNC_END(4, "grayObject (young gen, is old)");
return;
}
GC_TRACE_MARK(4, obj);
OBJ_SET_DARK(obj);
if (!inYoungGC) {
INC_GEN(obj);
}
// add object to gray stack
if (vm.grayCapacity < vm.grayCount+1) {
GC_TRACE_DEBUG(5, "Allocating more space for grayStack");
vm.grayCapacity = GROW_CAPACITY(vm.grayCapacity);
// Not using reallocate() here because we don't want to trigger the GC
// inside a GC!
vm.grayStack = realloc(vm.grayStack, sizeof(Obj*) * vm.grayCapacity);
ASSERT_MEM(vm.grayStack);
}
vm.grayStack[vm.grayCount++] = obj;
TRACE_GC_FUNC_END(4, "grayObject");
}
void grayValue(Value val) {
if (!IS_OBJ(val)) return;
TRACE_GC_FUNC_START(4, "grayValue");
grayObject(AS_OBJ(val));
TRACE_GC_FUNC_END(4, "grayValue");
}
/*static void grayArray(ValueArray *ary) {*/
/*TRACE_GC_FUNC_START(5, "grayArray");*/
/*for (int i = 0; i < ary->count; i++) {*/
/*grayValue(ary->values[i]);*/
/*}*/
/*TRACE_GC_FUNC_END(5, "grayArray");*/
/*}*/
// recursively gray an object's references
void blackenObject(Obj *obj) {
if (UNLIKELY(obj->type == OBJ_T_NONE)) return;
TRACE_GC_FUNC_START(4, "blackenObject");
switch (obj->type) {
case OBJ_T_BOUND_METHOD: {
GC_TRACE_DEBUG(5, "Blackening bound method %p", obj);
ObjBoundMethod *method = (ObjBoundMethod*)obj;
grayValue(method->receiver);
grayObject(method->callable);
break;
}
case OBJ_T_CLASS: {
GC_TRACE_DEBUG(5, "Blackening class %p (%s)", obj, className((ObjClass*)obj));
ObjClass *klass = (ObjClass*)obj;
if (klass->klass) {
grayObject((Obj*)klass->klass);
}
if (klass->singletonKlass) {
grayObject((Obj*)klass->singletonKlass);
}
if (klass->finalizerFunc) {
grayObject(klass->finalizerFunc);
}
if (klass->classInfo->name) {
grayObject((Obj*)klass->classInfo->name);
}
if (klass->classInfo->superclass) {
grayObject((Obj*)klass->classInfo->superclass);
}
// TODO: blacken included modules
grayTable(klass->fields);
grayTable(klass->classInfo->methods);
grayTable(klass->classInfo->getters);
grayTable(klass->classInfo->setters);
grayTable(klass->classInfo->constants);
break;
}
case OBJ_T_MODULE: {
ObjModule *mod = (ObjModule*)obj;
GC_TRACE_DEBUG(5, "Blackening module %p", mod);
if (mod->klass) {
GC_TRACE_DEBUG(8, "Graying module class");
grayObject((Obj*)mod->klass);
}
if (mod->singletonKlass) {
GC_TRACE_DEBUG(8, "Graying module singleton class");
grayObject((Obj*)mod->singletonKlass);
}
if (mod->finalizerFunc) {
GC_TRACE_DEBUG(8, "Graying module finalizer");
grayObject(mod->finalizerFunc);
}
if (mod->classInfo->name) {
GC_TRACE_DEBUG(8, "Graying module name");
grayObject((Obj*)mod->classInfo->name);
}
grayTable(mod->fields);
grayTable(mod->classInfo->methods);
grayTable(mod->classInfo->getters);
grayTable(mod->classInfo->setters);
grayTable(mod->classInfo->constants);
break;
}
case OBJ_T_ICLASS: {
ObjIClass *iklass = (ObjIClass*)obj;
grayObject((Obj*)iklass->mod);
grayObject((Obj*)iklass->klass);
grayObject(iklass->superklass);
break;
}
case OBJ_T_FUNCTION: {
GC_TRACE_DEBUG(5, "Blackening function %p", obj);
ObjFunction *func = (ObjFunction*)obj;
if (func->name) {
grayObject(TO_OBJ(func->name));
}
grayTable(&func->localsTable);
LocalVariable *var; int idx = 0;
vec_foreach(&func->variables, var, idx) {
grayObject(TO_OBJ(var->name));
}
break;
}
case OBJ_T_CLOSURE: {
GC_TRACE_DEBUG(5, "Blackening closure %p", obj);
ObjClosure *closure = (ObjClosure*)obj;
grayObject((Obj*)closure->function);
for (int i = 0; i < closure->upvalueCount; i++) {
grayObject((Obj*)closure->upvalues[i]); // closed upvalues
}
break;
}
case OBJ_T_SCOPE: {
GC_TRACE_DEBUG(5, "Blackening scope %p", obj);
ObjScope *scope = (ObjScope*)obj;
grayObject(TO_OBJ(scope->function));
for (int i = 0; i < scope->localsTable.size; i++) {
grayValue(scope->localsTable.tbl[i]);
}
break;
}
case OBJ_T_NATIVE_FUNCTION: {
ObjNative *native = (ObjNative*)obj;
GC_TRACE_DEBUG(5, "Blackening native function %p", obj);
grayObject((Obj*)native->name);
grayObject((Obj*)native->klass);
break;
}
case OBJ_T_INSTANCE: {
ObjInstance *instance = (ObjInstance*)obj;
GC_TRACE_DEBUG(5, "Blackening instance %p, class: %s", obj, className(instance->klass));
grayObject((Obj*)instance->klass);
if (instance->singletonKlass) {
grayObject((Obj*)instance->singletonKlass);
}
if (instance->finalizerFunc) {
grayObject(instance->finalizerFunc);
}
GC_TRACE_DEBUG(5, "Blackening instance fields");
grayTable(instance->fields);
if (instance->internal && instance->internal->markFunc) {
GC_TRACE_DEBUG(5, "Blackening instance internal (markFunc)");
instance->internal->markFunc((Obj*)instance->internal);
}
break;
}
case OBJ_T_ARRAY: {
GC_TRACE_DEBUG(5, "Blackening array %p", obj);
ObjArray *ary = (ObjArray*)obj;
ValueArray *valAry = &ary->valAry;
grayObject((Obj*)ary->klass);
if (ary->singletonKlass) {
grayObject((Obj*)ary->singletonKlass);
}
if (ary->finalizerFunc) {
grayObject(ary->finalizerFunc);
}
grayTable(ary->fields);
GC_TRACE_DEBUG(5, "Array count: %ld", valAry->count);
// NOTE: right now, shared arrays only point to static arrays,
// which only contain constants, so we can skip the graying of
// these non-objects.
if (!ARRAY_IS_SHARED(ary)) {
for (int i = 0; i < valAry->count; i++) {
Value val = valAry->values[i];
grayValue(val);
}
}
break;
}
case OBJ_T_MAP: {
GC_TRACE_DEBUG(5, "Blackening map %p", obj);
ObjMap *map = (ObjMap*)obj;
grayObject((Obj*)map->klass);
if (map->singletonKlass) {
grayObject((Obj*)map->klass);
}
if (map->finalizerFunc) {
grayObject(map->finalizerFunc);
}
grayTable(map->fields);
grayTable(map->table);
break;
}
case OBJ_T_REGEX: {
GC_TRACE_DEBUG(5, "Blackening regex %p", obj);
ObjRegex *reObj = (ObjRegex*)obj;
grayObject((Obj*)reObj->klass);
if (reObj->singletonKlass) {
grayObject((Obj*)reObj->klass);
}
if (reObj->finalizerFunc) {
grayObject(reObj->finalizerFunc);
}
grayTable(reObj->fields);
break;
}
case OBJ_T_INTERNAL: {
GC_TRACE_DEBUG(5, "Blackening internal object %p", obj);
ObjInternal *internal = (ObjInternal*)obj;
if (internal->markFunc) {
internal->markFunc(obj);
}
break;
}
case OBJ_T_UPVALUE: {
GC_TRACE_DEBUG(5, "Blackening upvalue object %p", obj);
grayValue(((ObjUpvalue*)obj)->closed);
break;
}
case OBJ_T_STRING: { // no references
ObjString *str = (ObjString*)obj;
if (str->klass) {
grayObject((Obj*)str->klass);
}
if (str->singletonKlass) {
grayObject((Obj*)str->singletonKlass);
}
if (str->finalizerFunc) {
grayObject((Obj*)str->finalizerFunc);
}
grayTable(str->fields);
GC_TRACE_DEBUG(5, "Blackening string %p", obj);
break;
}
default: {
UNREACHABLE("Unknown object type: %d", obj->type);
}
}
TRACE_GC_FUNC_END(4, "blackenObject");
}
static size_t sizeofObj(Obj *obj) {
return sizeofObjType(obj->type);
}
void freeObject(Obj *obj) {
if (UNLIKELY(obj->type == OBJ_T_NONE)) {
GC_TRACE_DEBUG(5, "freeObject called on OBJ_T_NONE: %p", obj);
return; // already freed
}
ASSERT(!OBJ_IS_HIDDEN(obj));
TRACE_GC_FUNC_START(4, "freeObject");
GC_TRACE_FREE(4, obj);
if (LIKELY(GCStats.generations[obj->GCGen])) {
GCStats.generations[obj->GCGen]--;
}
GCStats.heapUsed -= sizeof(ObjAny);
GCStats.heapUsedWaste -= (sizeof(ObjAny)-sizeofObj(obj));
GCStats.demographics[obj->type]--;
switch (obj->type) {
case OBJ_T_BOUND_METHOD: {
// NOTE: don't free the actual underlying function, we need this
// to stick around if only the bound method needs freeing
GC_TRACE_DEBUG(5, "Freeing bound method: p=%p", obj);
obj->type = OBJ_T_NONE;
break;
}
case OBJ_T_CLASS: {
ObjClass *klass = (ObjClass*)obj;
GC_TRACE_DEBUG(5, "Freeing class methods/getters/setters tables");
freeTable(klass->fields);
FREE_ARRAY(Table, klass->fields, 1);
freeClassInfo(klass->classInfo);
FREE(ClassInfo, klass->classInfo);
GC_TRACE_DEBUG(5, "Freeing class: p=%p", obj);
obj->type = OBJ_T_NONE;
break;
}
case OBJ_T_MODULE: {
ObjModule *mod = (ObjModule*)obj;
GC_TRACE_DEBUG(5, "Freeing module methods/getters/setters tables");
freeTable(mod->fields);
FREE_ARRAY(Table, mod->fields, 1);
freeClassInfo(mod->classInfo);
FREE(ClassInfo, mod->classInfo);
GC_TRACE_DEBUG(5, "Freeing module: p=%p", obj);
obj->type = OBJ_T_NONE;
break;
}
case OBJ_T_ICLASS: {
GC_TRACE_DEBUG(5, "Freeing iclass");
obj->type = OBJ_T_NONE;
break;
}
case OBJ_T_FUNCTION: {
ObjFunction *func = (ObjFunction*)obj; (void)func;
GC_TRACE_DEBUG(5, "Freeing ObjFunction chunk: p=%p", &func->chunk);
// FIXME: right now, multiple function objects can refer to the same
// chunk, due to how chunks are passed around and copied by value
// (I think this is the reason). Freeing them right now results in
// double free errors.
ASSERT(func->chunk);
freeChunk(func->chunk);
FREE(Chunk, func->chunk);
freeTable(&func->localsTable);
Scope *scope; int sidx = 0;
vec_foreach(&func->scopes, scope, sidx) {
FREE(Scope, scope);
}
LocalVariable *var; int vidx = 0;
vec_foreach(&func->variables, var, vidx) {
FREE(LocalVariable, var);
}
vec_deinit(&func->scopes);
vec_deinit(&func->variables);
FREE_SIZE(sizeof(Upvalue)*LX_MAX_UPVALUES, func->upvaluesInfo);
if (func->programNode) {
freeNode(func->programNode, true);
}
GC_TRACE_DEBUG(5, "Freeing ObjFunction: p=%p", obj);
obj->type = OBJ_T_NONE;
break;
}
case OBJ_T_CLOSURE: {
ObjClosure *closure = (ObjClosure*)obj;
GC_TRACE_DEBUG(5, "Freeing ObjClosure: p=%p", closure);
FREE_ARRAY(Value, closure->upvalues, closure->upvalueCount);
obj->type = OBJ_T_NONE;
break;
}