Skip to content

Commit fd45e26

Browse files
committed
runtime: warn that KeepAlive is not an unsafe.Pointer workaround
Even experienced users occasionally mistake that runtime.KeepAlive can be used as a workaround for following the unsafe.Pointer safety rules, but it cannot. Add an explicit warning to this effect to dissuade users from trying to use it as such. Fixes #47562. Change-Id: I842e33a3e1c080933c6b1bd1b6318448adbf495c Reviewed-on: https://go-review.googlesource.com/c/go/+/340269 Trust: Matthew Dempsky <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]>
1 parent 6e73886 commit fd45e26

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

src/runtime/mfinal.go

+4
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,10 @@ okarg:
466466
// Without the KeepAlive call, the finalizer could run at the start of
467467
// syscall.Read, closing the file descriptor before syscall.Read makes
468468
// the actual system call.
469+
//
470+
// Note: KeepAlive should only be used to prevent finalizers from
471+
// running prematurely. In particular, when used with unsafe.Pointer,
472+
// the rules for valid uses of unsafe.Pointer still apply.
469473
func KeepAlive(x interface{}) {
470474
// Introduce a use of x that the compiler can't eliminate.
471475
// This makes sure x is alive on entry. We need x to be alive

0 commit comments

Comments
 (0)