Garbage Collection:mark-sweep 与对象可达性
Crafting Interpreters:Garbage Collection
本章为 clox 实现 mark-sweep garbage collector:从根集合追踪可达对象,清扫不可达对象,并在合适时机触发回收。
TL;DR
- reachable object 是从 roots 沿 object references 可达的对象;不可达对象可以安全释放。
- mark-sweep 分为 mark 和 sweep:先标记可达对象,再遍历 heap 释放未标记对象。
- 三色抽象用 white、gray、black 表示 tracing 状态;gray worklist 保存已发现但尚未扫描引用的对象。
- VM stack、globals、call frames、compiler 临时对象和 intern table 都可能是 GC roots。
- 分配期间必须保护临时对象,否则 GC 可能在对象尚未连接到 root 时错误回收它。
目录
| 章节 | 内容 |
|---|---|
| Reachability | 可达性与 roots |
| Mark-sweep garbage collection | 标记与清扫 |
| Marking the roots | 根集合 |
| Tracing object references | 三色 tracing |
| Sweeping unused objects | 释放对象 |
| When to collect | 触发策略 |
| Garbage collection bugs | 临时对象保护 |
| Challenges | 扩展练习 |
| Design Note:Generational Collectors | 分代 GC |
Reachability
GC 的核心问题不是“对象多久没用”,而是从程序仍然持有的 roots 是否能走到该对象。stack 中的 script、closure 和 value 可能引用更多 object:

从 closure 沿 fields、upvalues 和 function references 追踪,就能得到全部 reachable objects:

不可达对象仍占用 heap,但程序再也无法观察它们,因此可以回收。
Mark-sweep garbage collection
mark-sweep 先从 roots 开始标记对象,再扫描整个 allocated object list,释放未标记对象并清除已标记状态:

Collecting garbage
collectGarbage() 的主要阶段是 markRoots、traceReferences 和 sweep。GC 不移动对象,所以 C pointer 在回收后仍指向原对象;但指向 white object 的 dangling pointer 必须在 mark 前被避免。
Debug logging
debug build 可以记录 GC 开始前 heap bytes、标记对象数量、释放对象数量和结束后的 bytes。日志能帮助发现 root 遗漏、对象未释放和触发频率异常。
Marking the roots
VM stack 是最明显的 root:其中每个 Value 都可能是 object pointer。globals table、call frames 中的 function/closure、open upvalues 和 compiler 正在构建的 function 也必须标记。

Less obvious roots
编译过程中,constant table 和刚创建但尚未放入 table/stack 的 Obj 可能只有 C 局部变量持有。分配新对象后若立刻触发 GC,必须先将它 push 到 VM stack 或加入临时 root,否则会被回收。
Tracing object references
标记一个 object 只证明它被发现;还要扫描它内部引用的 objects。ObjString 没有进一步引用,ObjFunction 需要扫描 name 与 constants,ObjClosure 需要扫描 function 和 upvalues。
The tricolor abstraction
三色状态表示 tracing 进度:
white:尚未发现。
gray:已发现,但内部引用尚未扫描。
black:已发现,内部所有引用都已扫描。
A worklist for gray objects
如果递归 tracing,深 object graph 可能耗尽 C call stack。clox 用 gray stack 作为 worklist:markObject 把 white object 变 gray 并压入;traceReferences 不断弹出 gray object 并处理。

Processing gray objects
blackenObject() 根据 object type 扫描内部引用,并调用 markObject。处理完成后把 object 标为 black。GC invariant 是:black object 不能指向 white object;增量或并发 GC 需要额外 write barrier 维护这个 invariant。
Sweeping unused objects
sweep 遍历 VM 的 allocated object linked list。white object 释放并从链表摘除;black object 重置为 white,留到下一次 GC。释放顺序必须先清理 object 专属资源,再释放 object memory。

Weak references and the string pool
intern table 不应强行保持所有 string 永久存活。若 string pool 是 weak 的,GC 在 mark 完成后可以清除其中指向 white string 的 entries,否则短暂创建的大量字符串会泄漏为逻辑上的永久对象。
When to collect
GC 可以在每次分配前检查 bytesAllocated 是否超过 nextGC。阈值通常根据上次存活 heap size 乘以 growth factor 调整。
Latency and throughput
GC 运行会暂停用户 code。单次 GC 越长,latency 越高;GC 总时间越多,应用 throughput 越低:

clox 使用 stop-the-world collector,优先保持实现简单。更复杂的 incremental 或 concurrent collector 可以降低 pause,但需要 write barrier 和更复杂的状态机。
Self-adjusting heap
如果每次回收后存活对象都很多,固定阈值会频繁 GC;如果存活对象很少,阈值过大又会浪费内存。根据 live bytes 自适应 nextGC,可以在内存和吞吐之间取得更稳定的平衡。
Garbage collection bugs
Adding to the constant table
constant table 的 grow、创建 string 和写入 table 之间可能触发 GC。临时 value 在加入可达结构前必须被保护。
Interning strings
interning 先分配 ObjString,再查询 table、插入 table。任何中间步骤都要保持 object reachable;否则 GC 会回收正在使用的 key。
Concatenating strings
concatenate 会分配 chars buffer 和 ObjString,并暂时持有 left/right/new object。实现应在每次可能分配前保护已有引用,完成后再恢复 stack。
Challenges
1. Incremental collection
把 mark 阶段分成多个小片段,在 VM 执行若干 instruction 后继续 tracing。
2. Generational collection
为 young objects 单独设置 nursery,比较短命对象快速回收与 write barrier 的成本。
3. Heap profiler
记录每种 object type 的分配量、存活量和平均生命周期,输出可用于定位泄漏的报告。
Design Note:Generational Collectors
许多程序遵循 generational hypothesis:大多数新对象很快死亡,少数对象会存活很久。分代 collector 可以频繁扫描 young generation,而较少扫描 old generation,从而降低平均成本。
代价是 old-to-young 引用必须被记录,否则 tracing young generation 会漏掉由老对象持有的新对象。write barrier、remembered set 和 promotion 策略都增加了实现复杂度;只有对象数量和分配模式确实值得时,分代设计才有收益。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
var a = "first value";
a = "updated";
// GC here.
print a;
Code block 2
var global = "string";
{
var local = "another";
print global + local;
}
Code block 3
fun makeClosure() {
var a = "data";
fun f() { print a; }
return f;
}
{
var closure = makeClosure();
// GC here.
closure();
}
Code block 4
void* reallocate(void* pointer, size_t oldSize, size_t newSize);
Code block 5
void collectGarbage();
Code block 6
void freeObjects();
Code block 7
void collectGarbage() {
}
Code block 8
#define DEBUG_TRACE_EXECUTION
Code block 9
#define DEBUG_STRESS_GC
Code block 10
#define UINT8_COUNT (UINT8_MAX + 1)
Code block 11
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
Code block 12
if (newSize > oldSize) {
#ifdef DEBUG_STRESS_GC
collectGarbage();
#endif
}
Code block 13
if (newSize == 0) {
Code block 14
#define DEBUG_STRESS_GC
Code block 15
#define DEBUG_LOG_GC
Code block 16
#define UINT8_COUNT (UINT8_MAX + 1)
Code block 17
#include "vm.h"
Code block 18
#ifdef DEBUG_LOG_GC
#include <stdio.h>
#include "debug.h"
#endif
Code block 19
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
Code block 20
void collectGarbage() {
Code block 21
#ifdef DEBUG_LOG_GC
printf("-- gc begin\n");
#endif
Code block 22
}
Code block 23
printf("-- gc begin\n");
#endif
Code block 24
#ifdef DEBUG_LOG_GC
printf("-- gc end\n");
#endif
Code block 25
}
Code block 26
vm.objects = object;
Code block 27
#ifdef DEBUG_LOG_GC
printf("%p allocate %zu for %d\n", (void*)object, size, type);
#endif
Code block 28
return object;
Code block 29
static void freeObject(Obj* object) {
Code block 30
#ifdef DEBUG_LOG_GC
printf("%p free type %d\n", (void*)object, object->type);
#endif
Code block 31
switch (object->type) {
Code block 32
#ifdef DEBUG_LOG_GC
printf("-- gc begin\n");
#endif
Code block 33
markRoots();
Code block 34
#ifdef DEBUG_LOG_GC
Code block 35
static void markRoots() {
for (Value* slot = vm.stack; slot < vm.stackTop; slot++) {
markValue(*slot);
}
}
Code block 36
void* reallocate(void* pointer, size_t oldSize, size_t newSize);
Code block 37
void markValue(Value value);
Code block 38
void collectGarbage();
Code block 39
void markValue(Value value) {
if (IS_OBJ(value)) markObject(AS_OBJ(value));
}
Code block 40
void* reallocate(void* pointer, size_t oldSize, size_t newSize);
Code block 41
void markObject(Obj* object);
Code block 42
void markValue(Value value);
Code block 43
void markObject(Obj* object) {
if (object == NULL) return;
object->isMarked = true;
}
Code block 44
ObjType type;
Code block 45
bool isMarked;
Code block 46
struct Obj* next;
Code block 47
object->type = type;
Code block 48
object->isMarked = false;
Code block 49
object->next = vm.objects;
Code block 50
void markObject(Obj* object) {
if (object == NULL) return;
Code block 51
#ifdef DEBUG_LOG_GC
printf("%p mark ", (void*)object);
printValue(OBJ_VAL(object));
printf("\n");
#endif
Code block 52
object->isMarked = true;
Code block 53
markValue(*slot);
}
Code block 54
markTable(&vm.globals);
Code block 55
}
Code block 56
ObjString* tableFindString(Table* table, const char* chars,
int length, uint32_t hash);
Code block 57
void markTable(Table* table);
Code block 58
#endif
Code block 59
void markTable(Table* table) {
for (int i = 0; i < table->capacity; i++) {
Entry* entry = &table->entries[i];
markObject((Obj*)entry->key);
markValue(entry->value);
}
}
Code block 60
}
Code block 61
for (int i = 0; i < vm.frameCount; i++) {
markObject((Obj*)vm.frames[i].closure);
}
Code block 62
markTable(&vm.globals);
Code block 63
for (int i = 0; i < vm.frameCount; i++) {
markObject((Obj*)vm.frames[i].closure);
}
Code block 64
for (ObjUpvalue* upvalue = vm.openUpvalues;
upvalue != NULL;
upvalue = upvalue->next) {
markObject((Obj*)upvalue);
}
Code block 65
markTable(&vm.globals);
Code block 66
markTable(&vm.globals);
Code block 67
markCompilerRoots();
Code block 68
}
Code block 69
ObjFunction* compile(const char* source);
Code block 70
void markCompilerRoots();
Code block 71
#endif
Code block 72
#include <stdlib.h>
Code block 73
#include "compiler.h"
Code block 74
#include "memory.h"
Code block 75
void markCompilerRoots() {
Compiler* compiler = current;
while (compiler != NULL) {
markObject((Obj*)compiler->function);
compiler = compiler->enclosing;
}
}
Code block 76
#include "compiler.h"
Code block 77
#include "memory.h"
Code block 78
#include "scanner.h"
Code block 79
object->isMarked = true;
Code block 80
if (vm.grayCapacity < vm.grayCount + 1) {
vm.grayCapacity = GROW_CAPACITY(vm.grayCapacity);
vm.grayStack = (Obj**)realloc(vm.grayStack,
sizeof(Obj*) * vm.grayCapacity);
}
vm.grayStack[vm.grayCount++] = object;
Code block 81
}
Code block 82
Obj* objects;
Code block 83
int grayCount;
int grayCapacity;
Obj** grayStack;
Code block 84
} VM;
Code block 85
vm.objects = NULL;
Code block 86
vm.grayCount = 0;
vm.grayCapacity = 0;
vm.grayStack = NULL;
Code block 87
initTable(&vm.globals);
Code block 88
object = next;
}
Code block 89
free(vm.grayStack);
Code block 90
}
Code block 91
vm.grayStack = (Obj**)realloc(vm.grayStack,
sizeof(Obj*) * vm.grayCapacity);
Code block 92
if (vm.grayStack == NULL) exit(1);
Code block 93
}
Code block 94
markRoots();
Code block 95
traceReferences();
Code block 96
#ifdef DEBUG_LOG_GC
Code block 97
static void traceReferences() {
while (vm.grayCount > 0) {
Obj* object = vm.grayStack[--vm.grayCount];
blackenObject(object);
}
}
Code block 98
static void blackenObject(Obj* object) {
switch (object->type) {
case OBJ_NATIVE:
case OBJ_STRING:
break;
}
}
Code block 99
static void blackenObject(Obj* object) {
switch (object->type) {
Code block 100
case OBJ_UPVALUE:
markValue(((ObjUpvalue*)object)->closed);
break;
Code block 101
case OBJ_NATIVE:
Code block 102
switch (object->type) {
Code block 103
case OBJ_FUNCTION: {
ObjFunction* function = (ObjFunction*)object;
markObject((Obj*)function->name);
markArray(&function->chunk.constants);
break;
}
Code block 104
case OBJ_UPVALUE:
Code block 105
static void markArray(ValueArray* array) {
for (int i = 0; i < array->count; i++) {
markValue(array->values[i]);
}
}
Code block 106
switch (object->type) {
Code block 107
case OBJ_CLOSURE: {
ObjClosure* closure = (ObjClosure*)object;
markObject((Obj*)closure->function);
for (int i = 0; i < closure->upvalueCount; i++) {
markObject((Obj*)closure->upvalues[i]);
}
break;
}
Code block 108
case OBJ_FUNCTION: {
Code block 109
static void blackenObject(Obj* object) {
Code block 110
#ifdef DEBUG_LOG_GC
printf("%p blacken ", (void*)object);
printValue(OBJ_VAL(object));
printf("\n");
#endif
Code block 111
switch (object->type) {
Code block 112
if (object == NULL) return;
Code block 113
if (object->isMarked) return;
Code block 114
#ifdef DEBUG_LOG_GC
Code block 115
traceReferences();
Code block 116
sweep();
Code block 117
#ifdef DEBUG_LOG_GC
Code block 118
static void sweep() {
Obj* previous = NULL;
Obj* object = vm.objects;
while (object != NULL) {
if (object->isMarked) {
previous = object;
object = object->next;
} else {
Obj* unreached = object;
object = object->next;
if (previous != NULL) {
previous->next = object;
} else {
vm.objects = object;
}
freeObject(unreached);
}
}
}
Code block 119
if (object->isMarked) {
Code block 120
object->isMarked = false;
Code block 121
previous = object;
Code block 122
traceReferences();
Code block 123
tableRemoveWhite(&vm.strings);
Code block 124
sweep();
Code block 125
ObjString* tableFindString(Table* table, const char* chars,
int length, uint32_t hash);
Code block 126
void tableRemoveWhite(Table* table);
Code block 127
void markTable(Table* table);
Code block 128
void tableRemoveWhite(Table* table) {
for (int i = 0; i < table->capacity; i++) {
Entry* entry = &table->entries[i];
if (entry->key != NULL && !entry->key->obj.isMarked) {
tableDelete(table, entry->key);
}
}
}
Code block 129
ObjUpvalue* openUpvalues;
Code block 130
size_t bytesAllocated;
size_t nextGC;
Code block 131
Obj* objects;
Code block 132
vm.objects = NULL;
Code block 133
vm.bytesAllocated = 0;
vm.nextGC = 1024 * 1024;
Code block 134
vm.grayCount = 0;
Code block 135
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
Code block 136
vm.bytesAllocated += newSize - oldSize;
Code block 137
if (newSize > oldSize) {
Code block 138
collectGarbage();
#endif
Code block 139
if (vm.bytesAllocated > vm.nextGC) {
collectGarbage();
}
Code block 140
}
Code block 141
sweep();
Code block 142
vm.nextGC = vm.bytesAllocated * GC_HEAP_GROW_FACTOR;
Code block 143
#ifdef DEBUG_LOG_GC
Code block 144
#endif
Code block 145
#define GC_HEAP_GROW_FACTOR 2
Code block 146
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
Code block 147
printf("-- gc begin\n");
Code block 148
size_t before = vm.bytesAllocated;
Code block 149
#endif
Code block 150
printf("-- gc end\n");
Code block 151
printf(" collected %zu bytes (from %zu to %zu) next at %zu\n",
before - vm.bytesAllocated, before, vm.bytesAllocated,
vm.nextGC);
Code block 152
#endif
Code block 153
int addConstant(Chunk* chunk, Value value) {
Code block 154
push(value);
Code block 155
writeValueArray(&chunk->constants, value);
Code block 156
writeValueArray(&chunk->constants, value);
Code block 157
pop();
Code block 158
return chunk->constants.count - 1;
Code block 159
#include "memory.h"
Code block 160
#include "vm.h"
Code block 161
void initChunk(Chunk* chunk) {
Code block 162
string->chars = chars;
string->hash = hash;
Code block 163
push(OBJ_VAL(string));
Code block 164
tableSet(&vm.strings, string, NIL_VAL);
Code block 165
tableSet(&vm.strings, string, NIL_VAL);
Code block 166
pop();
Code block 167
return string;
}
Code block 168
static void concatenate() {
Code block 169
ObjString* b = AS_STRING(peek(0));
ObjString* a = AS_STRING(peek(1));
Code block 170
int length = a->length + b->length;
Code block 171
ObjString* result = takeString(chars, length);
Code block 172
pop();
pop();
Code block 173
push(OBJ_VAL(result));
参考资料
- 原文:Garbage Collection
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)