~ach/hare

hare/rt/malloc+gc.ha -rw-r--r-- 10.2 KiB
a0bd4d20Andrew Chambers rt: Add an opt in garbage collector. a month ago
                                                                                
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
// License: MPL-2.0
// (c) 2021 Drew DeVault <sir@cmpwn.com>
// (c) 2021 Eyal Sawady <ecs@d2evs.net>
// (c) 2022 Andrew Chambers <ac@acha.ninja>

// This code is a runtime allocator that uses a conservative garbage collector
// to improve the safety of hare programs (by incurring runtime overhead).
// Library authors should never assume the presence of this runtime,
// but application authors could do so at their own discretion if the use case
// warrants it.
//
// The current implementation uses the allocator from malloc.ha, but also records
// allocations in an open addressed hash table. At allocation time, we then
// use a simple heap growth heuristic to trigger the mark and sweep phase.
// While marking it detects reachable pointers by conservatively scanning .data,
// .bss and stack and looking them up in the allocation table.
// Sweeping is a simple matter of checking which pointers in the allocation table
// are missing a mark (the low bit is set).
//
// Limitations:
// - The GC does not track pointers midway into heap objects (Uncommon anyway).
// - The GC is conservative so has a false positive rate.
// - You can still use stack objects past their lifetime, so its not total safety.

// Malloc implementation.

def ALIGN: size = 2;
def WORD: size = size(size);
def WASTE: size = WORD * ALIGN - WORD;
def BIGBLOCK: size = (2 << 16) * WORD;

let bins: [50]nullable *void = [null...];

fn bin2size(b: size) size = ((b + 1) * ALIGN - 1) * WORD;

fn size2bin(s: size) size = {
	assert(s <= bin2size(len(bins) - 1), "Size exceeds maximum for bin");
	return (s + (WORD * (ALIGN - 1) - 1)) / (WORD * ALIGN);
};

fn wrapped_malloc(n: size) nullable *void = {
	return if (n == 0) null
		else if (n > bin2size(len(bins) - 1)) malloc_large(n)
		else malloc_small(n);
};

fn malloc_large(n: size) nullable *void = {
	let p = segmalloc(n + WASTE + WORD);
	if (p == null) {
		return null;
	};
	let bsize = (p: uintptr + WASTE: uintptr): *[1]size;
	bsize[0] = n;
	return (p: uintptr + WASTE: uintptr + WORD: uintptr): nullable *void;
};

fn malloc_small(n: size) nullable *void = {
	const b = size2bin(n);
	let p = bins[b];
	if (p == null) {
		p = fill_bin(b);
		if (p != null) {
			bins[b] = p;
		};
	};
	return if (p != null) {
		let q = *(p: **void);
		bins[b] = q;
		yield p;
	} else null;
};

fn fill_bin(b: size) nullable *void = {
	const s = bin2size(b);
	let p = segmalloc(BIGBLOCK);
	return if (p == null) null else list_from_block(s, p: uintptr);
};

fn list_from_block(s: size, p: uintptr) nullable *void = {
	const nblocks = (BIGBLOCK - WASTE) / (s + WORD);

	let q = p + WASTE: uintptr; // align q+WORD
	for (let j = 0z; j != nblocks - 1; j += 1) {
		let sz = q: *size;
		let useralloc = q + WORD: uintptr; // aligned
		let next = (useralloc + s: uintptr + WORD: uintptr): *void;
		*sz = s;
		*(useralloc: **void) = next;
		q += s: uintptr + WORD: uintptr;
	};

	// Terminate last block:
	(q: *[1]size)[0] = s;
	*((q + 1: uintptr): *nullable *void) = null;

	// Return first block:
	return (p + WASTE: uintptr + WORD: uintptr): *void;
};

fn wrapped_free(_p: nullable *void) void = {
	if (_p != null) {
		let p = _p: *void;
		let bsize = (p: uintptr - size(size): uintptr): *[1]size;
		let s = bsize[0];
		if (s <= bin2size(len(bins) - 1)) free_small(p, s)
		else free_large(p, s);
	};
};

fn free_large(_p: *void, s: size) void = {
	let p = (_p: uintptr - (WASTE: uintptr + WORD: uintptr)): *void;
	segfree(p, s + WASTE + WORD);
};

fn free_small(p: *void, s: size) void = {
	let b = size2bin(s);
	let q = bins[b];
	*(p: *nullable *void) = q;
	bins[b] = p;
};

// Garbage collector implementation.

const MIN_COLLECT_THRESHOLD: size = 512*1024;
const ALLOCS_MIN_CAPACITY: size = 65536;
fn ptrhash(p: nullable *void) size = (p: uintptr >> 2) : size; // simply remove the zero bits.
fn threequarters(cap: size) size = (cap / 4) * 3;

type collector = struct {
	total_bytes: size,
	collect_threshold: size,
	allocs_count: size,
	allocs_count_max: size,
	allocs_cap: size,
	allocs: *[*]nullable *void,
};

let gc : collector = collector { ... };

@init fn init_gc() void = {
	gc.total_bytes = 0;
	gc.collect_threshold = MIN_COLLECT_THRESHOLD;
	gc.allocs_count = 0;
	gc.allocs_cap = ALLOCS_MIN_CAPACITY;
	gc.allocs_count_max = threequarters(gc.allocs_cap);
	let allocs = wrapped_malloc(gc.allocs_cap * size(uintptr));
	if (allocs is null) {
		abort();
	};
	gc.allocs = allocs as *[*]nullable *void;
};

fn alloc_size(ptr: nullable *void) size = {
	if (ptr is null) {
		return 0z;
	};
	let sz = (ptr: uintptr - size(size): uintptr): *[1]size;
	return sz[0];
};

fn resize_alloc_table(gc: *collector, cap: size) bool = {
	let count_max = threequarters(cap);
	let allocs = wrapped_malloc(cap * size(uintptr)); // XXX overflow
	if (allocs is null) {
		return false;
	};
	let allocs = allocs as *[*]nullable *void;
	for (let i = 0z; i < cap; i += 1) {
		allocs[i] = null;
	};
	for (let i = 0z; i < gc.allocs_cap; i += 1) {
		let ptr = gc.allocs[i];
		if (ptr is null) { 
			continue;
		};
		let idx = ptrhash(ptr) % cap;
		for (!(allocs[idx] is null) && allocs[idx] != ptr) {
			idx = (idx + 1) % gc.allocs_cap;
		};
		allocs[idx] = ptr;
	};
	wrapped_free(gc.allocs: *void);
	gc.allocs = allocs;
	gc.allocs_count_max = count_max;
	gc.allocs_cap = cap;
	return true;
};

fn grow_allocs_table(gc: *collector) bool = {
	return resize_alloc_table(gc, gc.allocs_cap*2);
};

fn track_pointer(gc: *collector, ptr: *void) bool = {
	if (gc.allocs_count+1 == gc.allocs_count_max) {
		if (!grow_allocs_table(gc)) {
			return false;
		};
	};
	let idx = ptrhash(ptr) % gc.allocs_cap;
	for (!(gc.allocs[idx] is null) && gc.allocs[idx] != ptr) {
		idx = (idx + 1) % gc.allocs_cap;
	};
	if (gc.allocs[idx] is null) {
		gc.allocs[idx] = ptr;
		gc.allocs_count += 1;
		gc.total_bytes += alloc_size(ptr);
	};
	return true;
};

fn get_stack_bottom() *[*]nullable *void = {
	// The environment is stored on the stack above main's frame,
	// this is a good approximation of the stack bottom.
	return envp : *[*]nullable *void;
};

fn get_stack_top() *[*]nullable *void = {
	// The top of the stack is just the address of a local variable.
	let dummy = 0z;
	return &dummy : *[*]nullable *void;
};

const @symbol("_sdata") data_start: [*]nullable *void;
const @symbol("_ebss") bss_end: [*]nullable *void;

fn mark(gc: *collector) void = {
	
	let mem = slice{ ... };
	
	let stack_top = get_stack_top();
	let stack_bottom = get_stack_bottom();

	let stack_low = stack_top;
	let stack_high = stack_bottom;
	if (stack_low: uintptr > stack_high: uintptr) {
		// Some architectures grow the stack in the other direction.
		let tmp = stack_high;
		stack_high = stack_low;
		stack_low = tmp;
	};

	let stack_size = (stack_high: uintptr - stack_low: uintptr) : size;

	mem.data = stack_low: nullable *void;
	mem.length = stack_size/size(uintptr);
	mem.capacity = mem.length;

	scan_memory(gc, *(&mem : *[]nullable *void));

	let data_size = (&bss_end: uintptr - &data_start: uintptr): size;
	mem.data = &data_start: nullable *void;
	mem.length = data_size/size(uintptr);
	mem.capacity = mem.length;

	scan_memory(gc, *(&mem : *[]nullable *void));
};

fn scan_memory(gc: *collector, mem: []nullable *void) void = {
	if (len(mem) == 0) {
		return;
	};
	for (let i = 0z; i < len(mem); i += 1) {
		let ptr = mem[i];
		if (ptr is null) {
			continue;
		};
		let idx = ptrhash(ptr) % gc.allocs_cap;
		for (!(gc.allocs[idx] is null) && (gc.allocs[idx]: uintptr & ~1) != ptr: uintptr) {
			idx = (idx + 1) % gc.allocs_cap;
		};
		if (gc.allocs[idx] is null) {
			continue;
		};
		if (gc.allocs[idx]: uintptr &1 == 1) {
			// Seen this pointer before.
			continue;	
		};
		// Set the low bit in the pointer to indicate 'marked'.
		gc.allocs[idx] = (gc.allocs[idx]: uintptr | 1): nullable *void;
		let heapsl = slice { ... };
		heapsl.data = ptr: nullable *void;
		heapsl.length = alloc_size(ptr) / size(uintptr);
		heapsl.capacity = heapsl.length;
		// XXX stack overflow on recursion, use worklist?.
		scan_memory(gc, *(&heapsl : *[]nullable *void));
	};
};

fn sweep(gc: *collector) void = {
	let n_reachable: size = 0;
	let total_bytes: size = 0;
	for (let i = 0z; i < gc.allocs_cap; i += 1) {
		let ptr = gc.allocs[i];
		if (ptr is null) {
			continue;
		};
		// Check and clear the mark bit, otherwise free.
		if (ptr: uintptr & 1 != 0) {
			gc.allocs[i] = (ptr: uintptr & ~1): nullable *void;
			n_reachable += 1;
			total_bytes += alloc_size(gc.allocs[i]);
		} else {
			wrapped_free(ptr);
			gc.allocs[i] = null;
		};
	};
	gc.total_bytes = total_bytes;
	gc.collect_threshold = gc.total_bytes * 2;
	if (gc.collect_threshold < MIN_COLLECT_THRESHOLD) {
		gc.collect_threshold = MIN_COLLECT_THRESHOLD;
	};
	gc.allocs_count = n_reachable;
	let cap = n_reachable * 2;
	if (cap < ALLOCS_MIN_CAPACITY) {
		cap = ALLOCS_MIN_CAPACITY;
	};
	if (!resize_alloc_table(gc, cap)) {
		abort(); // XXX out of memory, anything we can do?
	};
};

fn collect(gc: *collector) void = {
	// Use setjmp to save all registers
	// to the stack so they can be scanned.
	let buf = jmpbuf{ ... };

	if (setjmp(&buf) > 0) {
		return;
	};
	
	mark(gc);
	sweep(gc);

	// Using longjmp means the compiler
	// can't optimise away our jump buffer before
	// the mark phase completes.
	longjmp(&buf, 1);
};

fn gc_alloc(gc: *collector, sz: size) nullable *void = {
	match (wrapped_malloc(sz)) {
		case null => null;
		case let ptr: *void => {
			if (!track_pointer(gc, ptr)) {
				wrapped_free(ptr);
				return null;
			};
			if (gc.total_bytes > gc.collect_threshold) {
				collect(gc);
			};
			return ptr;
		};
	};
	return null;
};

fn gc_realloc(gc: *collector, ptr: nullable *void, sz: size) nullable *void = {
	if (ptr is null) {
		return gc_alloc(gc, sz);
	};
	let old_sz = alloc_size(ptr);
	if (old_sz >= sz) {
		return ptr;
	};
	let new_ptr = gc_alloc(gc, sz);
	match (gc_alloc(gc, sz)) {
		case null => return null;
		case let new: *void => {
			memcpy(new, ptr as *void, old_sz);
			return new;
		};
	};
};

export @symbol("rt.free") fn free_(ptr: nullable *void) void = {
	// Wipes memory, this means buggy code will likely experience a
	// safe crash (out of bounds or segfault) instead of continuing
	// in an inconsistent state.
	match (ptr) {
		case null => return;
		case let ptr: *void => memset(ptr, 0, alloc_size(ptr));
	};
};

export fn malloc(n: size) nullable *void = gc_alloc(&gc, n);
export fn realloc(ptr: nullable *void, n: size) nullable *void = gc_realloc(&gc, ptr, n);