go: x/sys: invalid use of unsafe.Pointer in ioctl arg parameters

From the documentation of unsafe.Pointer:

(4) Conversion of a Pointer to a uintptr when calling syscall.Syscall.

The Syscall functions in package syscall pass their uintptr arguments directly to the operating system, which then may, depending on the details of the call, reinterpret some of them as pointers. That is, the system call implementation is implicitly converting certain arguments back from uintptr to pointer.

If a pointer argument must be converted to uintptr for use as an argument, that conversion must appear in the call expression itself

Now, as far as I can tell this forces packages to adhere to exactly that.

The code in x/sys clearly violates that rule.

in unix/ioctl.go there’s

// IoctlSetPointerInt performs an ioctl operation which sets an
// integer value on fd, using the specified request number. The ioctl
// argument is called with a pointer to the integer value, rather than
// passing the integer value directly.
func IoctlSetPointerInt(fd int, req uint, value int) error {
        v := int32(value)
        return ioctl(fd, req, uintptr(unsafe.Pointer(&v)))
}

and the declaration of ioctl in zsyskall_linux.go:

func ioctl(fd int, req uint, arg uintptr) (err error) {
        _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
        if e1 != 0 {
                err = errnoErr(e1)
        }
        return
}

I’ve asked on the mailing list if that’s valid usage of unsafe, @ianlancetaylor wasn’t sure and told me to open an issue here for further discussion. (https://groups.google.com/g/golang-nuts/c/Ocpy8CKs7ZI/m/3ym8gnuBFgAJ)

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 1
  • Comments: 20 (11 by maintainers)

Commits related to this issue

Most upvoted comments

I don’t think that code is safe.

The ioctl function does not have any pragmas to mark it as a syscall function, so the compiler won’t know to do anything special for it. So the call to ioctl could potentially grow the stack, and then the arg pointer would be stale pointing to old memory.

I believe this is done, closing.

I believe the reason I didn’t close this before was because I only fixed it for Linux. Similar changes would have to be made for *BSD and etc.

I don’t think that code is safe.

The ioctl function does not have any pragmas to mark it as a syscall function, so the compiler won’t know to do anything special for it. So the call to ioctl could potentially grow the stack, and then the arg pointer would be stale pointing to old memory.

Hmm, so, whether it violates unsafe pointer rule?

Maybe the right fix is passing in an unsafe.Pointer instead of an uintptr 🤔