cgo's pointer check is all over the place
10 points by eatonphil
10 points by eatonphil
Good article. This covers the Go => C pointer checks but there are also C => Go pointer checks that can bite you.
The Go runtime treats anything typed as a pointer as a pointer, and the runtime can and will inspect it whenever it wants. If the value is garbage, the Go runtime hard crashes even if you never dereference it.
In building the Go bindings to libghostty, I discovered this, and it required changes in libghostty to properly fix it.
First, Zig uses sentinel addresses for various things, like 0x1 for empty slices. The contract of a slice is that if its length is zero, then the pointer is unsafe to use, so don't use it. Easy enough in general and totally fine in C. But in Go:
s := C.empty_string() // { ptr = (uint8_t*)0x1, len = 0 }
grow() // goroutine stack grows and gets copied
// fatal error: invalid pointer found on stack
When Go inspected the empty slice (at a grow point from the Go runtime), it found the 0x1 pointer to be garbage and hard crashed. The fix was to never return sentinels across the C ABI (commit).
The second one is nastier. In various places in the libghostty API, we would pass an uninitialized out-param to a Go callback, which stored a pointer to it. This is a small optimization to avoid the cost of zeroing memory, a common trick in C: if you know you're going to write to memory, why zero it? Pseudocode:
// out points at uninitialized C memory
out.data = pixels
// fatal error: found bad pointer in Go heap
In Go, while the GC is marking, the write barrier also looks at the value being overwritten. The problem is that Go doesn't know what is a pointer, so if the leftover bytes happen to look like a Go heap address, it aborts.
This shipped in code used by ~100,000 people daily and I never knew of a definite crash. But it luckily happened once in CI (after being in the code under test for over 9,000 total runs). After that, I ran it in a loop and reproduced it about 1 in 24,000 test runs. Fun!
The reason its so hard to reproduce is because the out.data = pixels has to happen WHILE the GC happens to be marking so that it hits a write barrier. Otherwise, its all fine.
The fix was zeroing the memory first, both in libghostty (commit) and in the bindings (commit).
To be fair, the cgo docs do say this, but it's one sentence and I missed it.
Hm I've always treated empty slices as {(void *)0, 0}. This obviously has the same semantics as {(void *), 0} from C; don't use the pointer if the length is 0. But what's the rationale for using 1 instead of 0 as the pointer value? Does {(void *)0, 0} represent something else in Ghostty?
My guess was that a segfault on a read to 0x0 could be all sorts of things, but a segfault on a read to 0x1 points more specifically to trying to read from slice without checking its length first.