目录
正在加载目录…
正在阅读专栏 Crafting Interpreters:手写解释器 第 29 篇 · 共 35 篇 · 83%

Garbage Collection:mark-sweep 与对象可达性

发布于 2026-09-16 19:26 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 5,563 · 预计阅读 12 分钟 👁 14 次阅读

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:

stack

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

reachable

不可达对象仍占用 heap,但程序再也无法观察它们,因此可以回收。

Mark-sweep garbage collection

mark-sweep 先从 roots 开始标记对象,再扫描整个 allocated object list,释放未标记对象并清除已标记状态:

mark sweep

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 也必须标记。

recycle

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 white:尚未发现。

gray gray:已发现,但内部引用尚未扫描。

black black:已发现,内部所有引用都已扫描。

A worklist for gray objects

如果递归 tracing,深 object graph 可能耗尽 C call stack。clox 用 gray stack 作为 worklist:markObject 把 white object 变 gray 并压入;traceReferences 不断弹出 gray object 并处理。

tricolor trace

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。

unlink

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 越低:

latency 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

c
var a = "first value";
a = "updated";
// GC here.
print a;

Code block 2

text
var global = "string";
{
  var local = "another";
  print global + local;
}

Code block 3

c
fun makeClosure() {
  var a = "data";

  fun f() { print a; }
  return f;
}

{
  var closure = makeClosure();
  // GC here.
  closure();
}

Code block 4

text
void* reallocate(void* pointer, size_t oldSize, size_t newSize);

Code block 5

c
void collectGarbage();

Code block 6

c
void freeObjects();

Code block 7

c
void collectGarbage() {
}

Code block 8

c
#define DEBUG_TRACE_EXECUTION

Code block 9

c
#define DEBUG_STRESS_GC

Code block 10

c
#define UINT8_COUNT (UINT8_MAX + 1)

Code block 11

text
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {

Code block 12

c
  if (newSize > oldSize) {
#ifdef DEBUG_STRESS_GC
    collectGarbage();
#endif
  }

Code block 13

c
  if (newSize == 0) {

Code block 14

c
#define DEBUG_STRESS_GC

Code block 15

c
#define DEBUG_LOG_GC

Code block 16

c
#define UINT8_COUNT (UINT8_MAX + 1)

Code block 17

c
#include "vm.h"

Code block 18

c
#ifdef DEBUG_LOG_GC
#include <stdio.h>
#include "debug.h"
#endif

Code block 19

text
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {

Code block 20

c
void collectGarbage() {

Code block 21

c
#ifdef DEBUG_LOG_GC
  printf("-- gc begin\n");
#endif

Code block 22

text
}

Code block 23

c
  printf("-- gc begin\n");
#endif

Code block 24

c
#ifdef DEBUG_LOG_GC
  printf("-- gc end\n");
#endif

Code block 25

text
}

Code block 26

text
  vm.objects = object;

Code block 27

c
#ifdef DEBUG_LOG_GC
  printf("%p allocate %zu for %d\n", (void*)object, size, type);
#endif

Code block 28

c
  return object;

Code block 29

c
static void freeObject(Obj* object) {

Code block 30

c
#ifdef DEBUG_LOG_GC
  printf("%p free type %d\n", (void*)object, object->type);
#endif

Code block 31

text
  switch (object->type) {

Code block 32

c
#ifdef DEBUG_LOG_GC
  printf("-- gc begin\n");
#endif

Code block 33

c
  markRoots();

Code block 34

c
#ifdef DEBUG_LOG_GC

Code block 35

c
static void markRoots() {
  for (Value* slot = vm.stack; slot < vm.stackTop; slot++) {
    markValue(*slot);
  }
}

Code block 36

text
void* reallocate(void* pointer, size_t oldSize, size_t newSize);

Code block 37

c
void markValue(Value value);

Code block 38

c
void collectGarbage();

Code block 39

c
void markValue(Value value) {
  if (IS_OBJ(value)) markObject(AS_OBJ(value));
}

Code block 40

text
void* reallocate(void* pointer, size_t oldSize, size_t newSize);

Code block 41

c
void markObject(Obj* object);

Code block 42

c
void markValue(Value value);

Code block 43

c
void markObject(Obj* object) {
  if (object == NULL) return;
  object->isMarked = true;
}

Code block 44

c
  ObjType type;

Code block 45

text
  bool isMarked;

Code block 46

c
  struct Obj* next;

Code block 47

text
  object->type = type;

Code block 48

text
  object->isMarked = false;

Code block 49

text
  object->next = vm.objects;

Code block 50

c
void markObject(Obj* object) {
  if (object == NULL) return;

Code block 51

c
#ifdef DEBUG_LOG_GC
  printf("%p mark ", (void*)object);
  printValue(OBJ_VAL(object));
  printf("\n");
#endif

Code block 52

text
  object->isMarked = true;

Code block 53

c
    markValue(*slot);
  }

Code block 54

c
  markTable(&vm.globals);

Code block 55

text
}

Code block 56

c
ObjString* tableFindString(Table* table, const char* chars,
                           int length, uint32_t hash);

Code block 57

c
void markTable(Table* table);

Code block 58

text
#endif

Code block 59

c
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

text
  }

Code block 61

c
  for (int i = 0; i < vm.frameCount; i++) {
    markObject((Obj*)vm.frames[i].closure);
  }

Code block 62

c
  markTable(&vm.globals);

Code block 63

c
  for (int i = 0; i < vm.frameCount; i++) {
    markObject((Obj*)vm.frames[i].closure);
  }

Code block 64

c
  for (ObjUpvalue* upvalue = vm.openUpvalues;
       upvalue != NULL;
       upvalue = upvalue->next) {
    markObject((Obj*)upvalue);
  }

Code block 65

c
  markTable(&vm.globals);

Code block 66

c
  markTable(&vm.globals);

Code block 67

c
  markCompilerRoots();

Code block 68

text
}

Code block 69

c
ObjFunction* compile(const char* source);

Code block 70

c
void markCompilerRoots();

Code block 71

text
#endif

Code block 72

c
#include <stdlib.h>

Code block 73

c
#include "compiler.h"

Code block 74

c
#include "memory.h"

Code block 75

c
void markCompilerRoots() {
  Compiler* compiler = current;
  while (compiler != NULL) {
    markObject((Obj*)compiler->function);
    compiler = compiler->enclosing;
  }
}

Code block 76

c
#include "compiler.h"

Code block 77

c
#include "memory.h"

Code block 78

c
#include "scanner.h"

Code block 79

text
  object->isMarked = true;

Code block 80

c
  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

text
}

Code block 82

c
  Obj* objects;

Code block 83

c
  int grayCount;
  int grayCapacity;
  Obj** grayStack;

Code block 84

c
} VM;

Code block 85

text
  vm.objects = NULL;

Code block 86

c
  vm.grayCount = 0;
  vm.grayCapacity = 0;
  vm.grayStack = NULL;

Code block 87

text
  initTable(&vm.globals);

Code block 88

text
    object = next;
  }

Code block 89

c
  free(vm.grayStack);

Code block 90

text
}

Code block 91

c
    vm.grayStack = (Obj**)realloc(vm.grayStack,
                                  sizeof(Obj*) * vm.grayCapacity);

Code block 92

c
    if (vm.grayStack == NULL) exit(1);

Code block 93

text
  }

Code block 94

c
  markRoots();

Code block 95

text
  traceReferences();

Code block 96

c
#ifdef DEBUG_LOG_GC

Code block 97

c
static void traceReferences() {
  while (vm.grayCount > 0) {
    Obj* object = vm.grayStack[--vm.grayCount];
    blackenObject(object);
  }
}

Code block 98

c
static void blackenObject(Obj* object) {
  switch (object->type) {
    case OBJ_NATIVE:
    case OBJ_STRING:
      break;
  }
}

Code block 99

c
static void blackenObject(Obj* object) {
  switch (object->type) {

Code block 100

c
    case OBJ_UPVALUE:
      markValue(((ObjUpvalue*)object)->closed);
      break;

Code block 101

text
    case OBJ_NATIVE:

Code block 102

text
  switch (object->type) {

Code block 103

c
    case OBJ_FUNCTION: {
      ObjFunction* function = (ObjFunction*)object;
      markObject((Obj*)function->name);
      markArray(&function->chunk.constants);
      break;
    }

Code block 104

text
    case OBJ_UPVALUE:

Code block 105

c
static void markArray(ValueArray* array) {
  for (int i = 0; i < array->count; i++) {
    markValue(array->values[i]);
  }
}

Code block 106

text
  switch (object->type) {

Code block 107

c
    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

text
    case OBJ_FUNCTION: {

Code block 109

c
static void blackenObject(Obj* object) {

Code block 110

c
#ifdef DEBUG_LOG_GC
  printf("%p blacken ", (void*)object);
  printValue(OBJ_VAL(object));
  printf("\n");
#endif

Code block 111

text
  switch (object->type) {

Code block 112

c
  if (object == NULL) return;

Code block 113

c
  if (object->isMarked) return;

Code block 114

c
#ifdef DEBUG_LOG_GC

Code block 115

text
  traceReferences();

Code block 116

c
  sweep();

Code block 117

c
#ifdef DEBUG_LOG_GC

Code block 118

c
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

c
    if (object->isMarked) {

Code block 120

text
      object->isMarked = false;

Code block 121

text
      previous = object;

Code block 122

text
  traceReferences();

Code block 123

text
  tableRemoveWhite(&vm.strings);

Code block 124

c
  sweep();

Code block 125

c
ObjString* tableFindString(Table* table, const char* chars,
                           int length, uint32_t hash);

Code block 126

c
void tableRemoveWhite(Table* table);

Code block 127

c
void markTable(Table* table);

Code block 128

c
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

c
  ObjUpvalue* openUpvalues;

Code block 130

c
  size_t bytesAllocated;
  size_t nextGC;

Code block 131

c
  Obj* objects;

Code block 132

text
  vm.objects = NULL;

Code block 133

c
  vm.bytesAllocated = 0;
  vm.nextGC = 1024 * 1024;

Code block 134

c
  vm.grayCount = 0;

Code block 135

text
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {

Code block 136

text
  vm.bytesAllocated += newSize - oldSize;

Code block 137

c
  if (newSize > oldSize) {

Code block 138

text
    collectGarbage();
#endif

Code block 139

c
    if (vm.bytesAllocated > vm.nextGC) {
      collectGarbage();
    }

Code block 140

text
  }

Code block 141

c
  sweep();

Code block 142

c
  vm.nextGC = vm.bytesAllocated * GC_HEAP_GROW_FACTOR;

Code block 143

c
#ifdef DEBUG_LOG_GC

Code block 144

text
#endif

Code block 145

c
#define GC_HEAP_GROW_FACTOR 2

Code block 146

text
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {

Code block 147

c
  printf("-- gc begin\n");

Code block 148

text
  size_t before = vm.bytesAllocated;

Code block 149

text
#endif

Code block 150

c
  printf("-- gc end\n");

Code block 151

c
  printf("   collected %zu bytes (from %zu to %zu) next at %zu\n",
         before - vm.bytesAllocated, before, vm.bytesAllocated,
         vm.nextGC);

Code block 152

text
#endif

Code block 153

c
int addConstant(Chunk* chunk, Value value) {

Code block 154

text
  push(value);

Code block 155

c
  writeValueArray(&chunk->constants, value);

Code block 156

c
  writeValueArray(&chunk->constants, value);

Code block 157

text
  pop();

Code block 158

c
  return chunk->constants.count - 1;

Code block 159

c
#include "memory.h"

Code block 160

c
#include "vm.h"

Code block 161

c
void initChunk(Chunk* chunk) {

Code block 162

text
  string->chars = chars;
  string->hash = hash;

Code block 163

text
  push(OBJ_VAL(string));

Code block 164

text
  tableSet(&vm.strings, string, NIL_VAL);

Code block 165

text
  tableSet(&vm.strings, string, NIL_VAL);

Code block 166

text
  pop();

Code block 167

c
  return string;
}

Code block 168

c
static void concatenate() {

Code block 169

c
  ObjString* b = AS_STRING(peek(0));
  ObjString* a = AS_STRING(peek(1));

Code block 170

text
  int length = a->length + b->length;

Code block 171

c
  ObjString* result = takeString(chars, length);

Code block 172

text
  pop();
  pop();

Code block 173

text
  push(OBJ_VAL(result));

参考资料

← 返回列表
← 上一篇 Closures:upvalue 捕获与生命周期 下一篇 → Classes and Instances:clox 对象与属性访问

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论