hn.today

Cgo's pointer check is all over the place

theconsensus.dev7 points0 comments
Screenshot of Cgo's pointer check is all over the place

The piece explains how cgo connects Go and C: it parses C references, generates Go and C bridge code, and routes calls through a runtime function with a single pointer argument. A C function with ordinary arguments therefore gets wrappers that package values into memory, call the C function, and return its result. The focus is what happens when Go pointers cross that boundary. Go permits passing a pointer to C only when the pointed-to memory contains no unpinned Go pointers, and C must not retain an unpinned Go pointer after the call. Since the garbage collector cannot safely track arbitrary C-held references, cgo adds runtime checks when it cannot establish safety at build time.

A worked example passes the address of a struct field that itself holds a Go pointer; the generated code inserts a check and panics. Pinning the nested object with runtime.Pinner makes the call succeed. The broader argument is that cgo’s checks are based on syntactic transformations rather than a full understanding of Go types. As a result, small changes in how an argument is written can alter whether legal code panics, how much checking occurs, or how slowly the call runs. The introduction reports that some equivalent-looking C calls can differ from 48 nanoseconds to 76 microseconds - about 1,600 times - and that the checker can be both costly and exhaustive in some cases yet fail to inspect others.

Read on theconsensus.dev0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.