Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/cgo: replace _Cgo_use with runtime.KeepAlive? #20281

Closed
josharian opened this issue May 8, 2017 · 4 comments

Comments

@josharian
Copy link
Contributor

commented May 8, 2017

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

@josharian josharian added this to the Go1.10 milestone May 8, 2017

@ianlancetaylor

This comment has been minimized.

Copy link
Contributor

commented May 8, 2017

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.

@josharian

This comment has been minimized.

Copy link
Contributor Author

commented May 8, 2017

Thanks, Ian. I think we have (or could easily add) an annotation for making parameters escape. Will dig and experiment.

@josharian josharian self-assigned this May 8, 2017

@bcmills

This comment has been minimized.

Copy link
Member

commented May 11, 2017

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.

@rsc

This comment has been minimized.

Copy link
Contributor

commented Nov 22, 2017

As established above, the answer is "no." Closing.

@rsc rsc closed this Nov 22, 2017

@golang golang locked and limited conversation to collaborators Nov 22, 2018

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
5 participants
You can’t perform that action at this time.