how to work around "go vet: possible misuse of unsafe.Pointer"?

1,316 views
Skip to first unread message

Kn

unread,
May 20, 2021, 3:37:35 AM5/20/21
to golang-nuts
Hi, guys, I need to acess shared memory, so I write some code like this:

```go
func shmget(key int, size int, mode int) (int, error) {
shmId, _, ret := syscall.Syscall(syscall.SYS_SHMGET, uintptr(key), uintptr(size), uintptr(mode))
if ret != 0 {
return 0, fmt.Errorf("shmget ret: %d", ret)
}
return int(shmId), nil
}

// shmat 映射共享内存地址到当前进程空间
func shmat(shmId int, addr unsafe.Pointer, flags int) (unsafe.Pointer, error) {
shmAddr, _, ret := syscall.Syscall(syscall.SYS_SHMAT, uintptr(shmId), uintptr(addr), uintptr(flags))
if ret != 0 {
return nil, fmt.Errorf("shmat ret: %d", ret)
}
return unsafe.Pointer(shmAddr), nil        // => possible misuse of unsafe.Pointer
}

func GetShm(iKey, iSize, iFlag int) (unsafe.Pointer, error) {
iShmID, err := shmget(iKey, iSize, iFlag)
if err != nil {
return nil, err
}
sShmPtr, err := shmat(iShmID, nil, iFlag)
if err != nil {
return nil, err
}
return sShmPtr, nil
}
```

When I run go vet to check this code, it reports "possible misuse of unsafe.Pointer" for the bold line "return unsafe.Pointer(shmaddr), nil" . And I have read the Pointer rules. I see this case isn't listed in the rules.

I want to know :
- is it safe to use pointer like this? I think syscall `shmat` returns the attached memory address that doesn't controlled by GC. I think it's safe.
- if it's safe, how could I work around this check? just neglect it or do we have some directives to prevent go vet checking?

Thanks.

Kn

unread,
May 20, 2021, 3:39:28 AM5/20/21
to golang-nuts
So sorry I didn't get how to format the code in the edit window.

Kn

unread,
May 20, 2021, 4:14:53 AM5/20/21
to golang-nuts
I found this issue: https://github.com/golang/go/issues/41205.

I found the answer, this conversation could be closed.

Reply all
Reply to author
Forward
0 new messages