You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Can _Cgo_use and all associated machinery and runtime checks be replaced with calls to runtime.KeepAlive? Seems like it would generate simpler and faster code.
They aren't the same thing. Given a pointer variable p, runtime.KeepAlive(p) ensures that the pointer is live--is not freed too early. Calling _Cgo_use, on the other hand, ensures that the pointer escapes--the value to which it points must be allocated on the heap. The goal of _Cgo_use is to make sure that pointers passed to C code escape. If they do not escape, the values to which they point may be allocated on the stack. Then if the C code calls back into Go code, and the Go code triggers a stack copy, the value might move, and when the Go code returns to C code the C code will be holding onto a dangling pointer.
There may be other ways to fix this problem--using segmented stacks for this specific case comes to mind--but simply using runtime.KeepAlive will not work.
This seems related to a discussion I had with @aclements last week.
The reason the arguments to cgo calls need to escape is because the Go stack may be resized during the call: if the C function calls back into Go, that call will resume on the same Go stack and might exhaust it. If we instead use a new Go stack for each call from C, we could exclude that possibility and treat every C function as implicitly noescape, and then runtime.KeepAlive might suffice.
Can _Cgo_use and all associated machinery and runtime checks be replaced with calls to runtime.KeepAlive? Seems like it would generate simpler and faster code.
@ianlancetaylor
The text was updated successfully, but these errors were encountered: